我正在使用下面的代码从网页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块,它给出了一个错误:未定义的变量: item。如果我想重新包含try -include块,我是否应该在try块之外给出一个变量,item的空白定义?
附言:请注意,这是一本书中的标准代码。我希望他们不会犯如此微不足道的错误。我是不是搞错了?
发布于 2013-01-12 00:37:51
try:
page = urllib2.urlopen(URL)
except urllib2.URLError:
print 'Failed to fetch ' + URL在第二个代码块中,也将item更改为URL (假设要显示的错误显示的是URL,而不是内容)。
try:
soup = BeautifulSoup(page)
except HTMLParser.HTMLParseError:
print 'Failed to parse ' + URL发布于 2013-01-12 00:38:07
print 'Failed to fetch ' + itemitem is not defined any .我猜您想要在那里打印URL。
根据python tutorial
在使用
变量之前,必须对其进行“定义”(赋值),否则将出现错误:
发布于 2013-01-12 00:51:08
您没有定义变量'item‘。这就是导致错误的原因。必须先定义变量,然后才能使用它。
https://stackoverflow.com/questions/14282577
复制相似问题