我正在使用以下代码从网页http://ajaxian.com抓取 XFN 内容, 但出现未定义变量错误:
我的代码如下:
'''
Created on Jan 11, 2013
@author: Somnath
'''
# Scraping XFN content from a web page
# -*-coding: utf-8 -*-
import sys
import urllib2
import HTMLParser
from BeautifulSoup import BeautifulSoup
# Try http://ajaxian.com
URL = sys.argv[0]
XFN_TAGS = set([
'colleague',
'sweetheart',
'parent',
'co-resident',
'co-worker',
'muse',
'neighbor',
'sibling',
'kin',
'child',
'date',
'spouse',
'me',
'acquaintance',
'met',
'crush',
'contact',
'friend',
])
try:
page = urllib2.urlopen(URL)
except urllib2.URLError:
print 'Failed to fetch ' + item
try:
soup = BeautifulSoup(page)
except HTMLParser.HTMLParseError:
print 'Failed to parse ' + item
anchorTags = soup.findAll('a')
for a in anchorTags:
if a.has_key('rel'):
if len(set(a['rel'].split()) & XFN_TAGS) > 0:
tags = a['rel'].split()
print a.contents[0], a['href'], tags
我的代码中有两个 try 块,它给出了一个错误 undefined variable : item. 如果我想重新包含 try-except 块,我应该在 try 块之外给出变量、项目的空白定义吗?
PS:请注意,这是一本书的标准代码。而且我希望他们不会犯如此微不足道的错误。我这里有什么问题吗?