【问题标题】:Python BeautifulSoup to csv scrapingPython BeautifulSoup 到 csv 抓取
【发布时间】:2016-08-08 17:51:30
【问题描述】:

我正在尝试从 html 页面中抓取一些简单的字典信息。到目前为止,我能够在 IDE 上打印我需要的所有单词。我的下一步是将单词转移到一个数组中。我的最后一步是将数组保存为 csv 文件......当我运行我的代码时,它似乎在第 1309 个或第 1311 个单词之后停止获取信息,尽管我相信网页上有超过 100 万个。我被困住了,非常感谢任何帮助。谢谢你

from bs4 import BeautifulSoup
from urllib import urlopen
import csv

html = urlopen('http://www.mso.anu.edu.au/~ralph/OPTED/v003/wb1913_a.html').read()

soup = BeautifulSoup(html,"lxml")

words = []

for section in soup.findAll('b'):

    words.append(section.renderContents())

print ('success')
print (len(words))

myfile = open('A.csv', 'wb')
wr = csv.writer(myfile)
wr.writerow(words)

【问题讨论】:

    标签: python csv web-scraping beautifulsoup


    【解决方案1】:

    我无法重现该问题(总是得到 11616 项),但我怀疑您安装了过时的 beautifulsoup4lxml 版本。升级:

    pip install --upgrade beautifulsoup4
    pip install --upgrade lxml
    

    当然,这只是一个理论。

    【讨论】:

      【解决方案2】:

      我怀疑您的大部分问题可能在于您如何处理抓取的内容。在将内容输出到文件之前是否需要抓取所有内容?或者你可以边做边做吗?

      您应该使用yield,而不是一遍又一遍地追加到列表中。

      def tokenize(soup_):
          for section in soup_.findAll('b'):
              yield section.renderContents()
      

      这会给你一个生成器,只要 section.renderContents() 返回一个字符串,csv 模块就可以毫无问题地写出来。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-20
        • 1970-01-01
        • 1970-01-01
        • 2013-09-28
        • 2016-01-01
        • 1970-01-01
        • 2020-09-02
        • 1970-01-01
        相关资源
        最近更新 更多