【问题标题】:Python, BeautifulSoup iterating through files issuePython,BeautifulSoup 遍历文件问题
【发布时间】: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


    【解决方案1】:

    你需要每次都追加而不是覆盖,使用aopen('lob.csv', 'wb')是通过你的外循环每次覆盖:

    writer = csv.writer(open('lob.csv', 'ab'))
    writer.writerows(list_of_rows)
    

    您还可以在 for 循环之外声明 list_of_rows = [] 并在最后写入文件一次。

    如果您想要第 30 页,还需要循环输入 range(22,31)

    【讨论】:

    • 太棒了!!太有帮助了! (虽然现在我们还有一个小问题,但我认为我可以处理!)
    • 不用担心,您看到倒数第二页的事实让我认为您也想要第 30 页,因此如上所述在您的范围内再添加一个。
    • 好的,谢谢!已经想出来了——但现在意识到 col[2] 和 col[3] 中的数字不会出现,除非它们是 0.00 美元;并且有一个关于 427 条记录的 unicode 错误......但谢谢!我可能会尝试在循环之外列出行列表,看看是否有效......
    • 在写入文件之前可能需要编码为 utf-8
    猜你喜欢
    • 2012-05-05
    • 2014-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 2017-11-27
    相关资源
    最近更新 更多