读完这个论坛后,我不确定哪种方法最好将部分数据提取到CSV文件中,即Python/Beautiful Soup/html2text。因为有大量的文件,所以我想尝试编写一个可以在终端中运行的脚本。
输出:一个CSV文件,包含一行文本和五列数据。例如第一行和最后一行
1002010-12-20 145 ABC 04110000
1 2010-11-10 133 DDD 041123847
谢谢!
发布于 2010-12-25 09:08:26
我推荐使用BeautifulSoup。像这样的东西就行了(完全未经测试)。有关更多信息,请阅读documentation。
csvfile = open('dump.csv', 'w')
for file in glob.glob('*.html'):
print 'Processing', file
soup = BeautifulSoup(open(file).read())
for tr in soup.findAll('tr'):
print >>csvfile, ' '.join(tr.findAll('td'))发布于 2010-12-25 09:08:10
我不知道Python本身是否支持XPath,但如果它支持,您应该在这个主题上做一些研究。
另一种替代解决方案是正则表达式。
发布于 2010-12-31 04:42:21
我已经将我的代码修改为:
#!/usr/bin/env python
import glob
import codecs
from BeautifulSoup import BeautifulSoup
with codecs.open('dump2.csv', "w", encoding="utf-8") as csvfile:
for file in glob.glob('*html*'):
print 'Processing', file
soup = BeautifulSoup(open(file).read())
rows = soup.findAll('tr')
for tr in rows:
cols = tr.findAll('td')
#print >> csvfile,"#".join(col.string for col in cols)
#print >> csvfile,"#".join(td.find(text=True))
for col in cols:
print >> csvfile, col.string
print >> csvfile, "==="
print >> csvfile, "***"代码现在使用*和===分隔符提取数据,然后使用perl将其放入一个干净的csv文件中。由于某种原因,它不会取出所有需要的数据,但会“遗漏”一些数据,例如Address1和Address2数据+表开头的日期和时间以及数字没有出来。
https://stackoverflow.com/questions/4528915
复制相似问题