【发布时间】:2016-03-31 14:01:01
【问题描述】:
我有一些从网站上提取的数据。这是我用来抓取它的代码(我的实际代码要长得多,但我认为这可以总结一下)。
lid_restrict_save = []
for t in range(10000,10020):
address = 'http://www.tspc.oregon.gov/lookup_application/' + lines2[t]
page = requests.get(address)
tree = html.fromstring(page.text)
#District Restriction
dist_restrict = tree.xpath('//tr[11]//text()')
if u"District Restriction" in dist_restrict:
lid_restrict_save.append(id2)
我正在尝试导出此列表:
print lid_restrict_save
[['5656966VP65', '5656966RR68', '56569659965', '56569658964']]
到一个文本文件。
f = open('dis_restrict_no_uniqDOB2.txt', 'r+')
for j in range(0,len(lid_restrict_save)):
s = ( (unicode(lid_restrict_save[j]).encode('utf-8') + ' \n' ))
f.write(s)
f.close()
我希望文本看起来像这样:
5656966VP65
5656966RR68
56569659965
56569658964
此代码有效,但仅当我从 0 开始 range 时。
f = open('dis_restrict.txt', 'r+')
for j in range(0,len(ldob_restrict)):
f.write( ldob_restrict[j].encode("utf-8") + ' \n' )
f.close()
当我尝试更改代码时,我不断收到此错误:
"AttributeError: 'list' object has no attribute 'encode'."
我尝试了here、here 和here 的建议,但无济于事。
如果有人有任何提示,将不胜感激。
【问题讨论】:
-
lid_restrict_save是一个嵌套列表。使用lid_restrict_save = lid_restrict_save[0] -
@Farhan.K 我收到了
IndexError: list index out of range。应该嵌套在循环内还是lid_restrict_save = []之下?
标签: python-2.7 encoding utf-8