【发布时间】:2014-12-16 23:45:02
【问题描述】:
这可能最终成为一个非常新手的问题,因为我是新手,但这里是。
我有一组使用 wget 获得的 .html 页面。我想遍历它们并提取某些信息,将其放入 .csv 文件中。
使用下面的代码,我的程序运行时会打印所有名称,但只有倒数第二页(即此处的第 29.html 页)的信息会打印到 .csv 文件。我一开始只用少数几个文件来尝试这个,大约有 1,200 个我想采用这种格式。
文件基于此处的文件:https://www.cfis.state.nm.us/media/ReportLobbyist.aspx?id=25&el=2014 其中页码是 id
感谢您的帮助!
from bs4 import BeautifulSoup
import urllib2
import csv
for i in xrange(22, 30):
try:
page = urllib2.urlopen('file:{}.html'.format(i))
except:
continue
else:
soup = BeautifulSoup(page.read())
n = soup.find(id='ctl00_ContentPlaceHolder1_lnkBCLobbyist')
name = n.string
print name
table = soup.find('table', 'reportTbl')
#get the rows
list_of_rows = []
for row in table.findAll('tr')[1:]:
col = row.findAll('td')
filing = col[0].string
status = col[1].string
cont = col[2].string
exp = col[3].string
record = (name, filing, status, cont, exp)
list_of_rows.append(record)
#write to file
writer = csv.writer(open('lob.csv', 'wb'))
writer.writerows(list_of_rows)
【问题讨论】:
标签: python loops csv beautifulsoup