Skip to content Skip to sidebar Skip to footer

Undefined Variable Defined Within Try-except Block

I am using the below code to scrape over XFN content from web page http://ajaxian.com but I am getting undefined variable error: My code is as follows: ''' Created on Jan 11, 2013

Solution 1:

Assuming that you want to print the URL that failed to load, try changing it to print 'Failed to fetch ' + URL. You aren't actually defining item anywhere, so Python doesn't know what you mean:

try:
    page = urllib2.urlopen(URL)
except urllib2.URLError:
    print'Failed to fetch ' + URL

And in your second block, change item to URL as well (assuming the error you want to display shows the URL and not the content).

try:
    soup = BeautifulSoup(page)
except HTMLParser.HTMLParseError:
    print'Failed to parse ' + URL

Solution 2:

print'Failed to fetch ' + item

item is not defined any where. I guess you wanted to print URL there.

As per python tutorial

Variables must be “defined” (assigned a value) before they can be used, or an error will occur:

Solution 3:

You did not define the variable 'item'. That's what is causing the error. You must define a variable before you use it.

Post a Comment for "Undefined Variable Defined Within Try-except Block"