使用ScraperWiki抓取PDF时出现未定义错误
我正在尝试用ScraperWiki来抓取这个PDF文件。现在的代码给我报了一个错误,提示“名字 'data' 未定义”,但是我在
elif int(el.attrib['left']) < 647: data['Neighborhood'] = el.text
如果我把那一行注释掉,我在else语句上也会收到同样的错误。
这是我的代码
import scraperwiki
import urllib2, lxml.etree
#Pull Mondays
url = 'http://www.city.pittsburgh.pa.us/police/blotter/blotter_monday.pdf'
pdfdata = urllib2.urlopen(url).read()
xmldata = scraperwiki.pdftoxml(pdfdata)
root = lxml.etree.fromstring(xmldata)
# how many pages in PDF
pages = list(root)
print "There are",len(pages),"pages"
# Test Scrape of only Page 1 of 29
for page in pages[0:1]:
for el in page:
if el.tag == "text":
if int(el.attrib['left']) < 11: data = { 'Report Name': el.text }
elif int(el.attrib['left']) < 317: data['Location of Occurrence'] = el.text
elif int(el.attrib['left']) < 169: data['Incident Time'] = el.text
elif int(el.attrib['left']) < 647: data['Neighborhood'] = el.text
elif int(el.attrib['left']) < 338: data['Description'] = el.text
else:
data['Zone'] = el.text
print data
我哪里出错了呢?
另外,如果有更好的解决方案,欢迎提供建议。
1 个回答
1
除非你跳过了某些代码,否则你的 data
字典只有在这一行的条件满足时才会被创建:
if int(el.attrib['left']) < 11: data = { 'Report Name': el.text }
你后面所有设置 data
值的代码都依赖于它已经存在,所以如果这个条件没有满足,你就会遇到 NameError
的错误。
一个简单的解决办法是总是先创建一个空的 data 字典,比如:
for page in pages[0:1]:
for el in page:
data = {}
if el.tag =="text":
等等。