【问题标题】:BeautifulSoup and Large htmlBeautifulSoup 和大 html
【发布时间】:2015-05-06 11:49:58
【问题描述】:

我试图抓取一些大型维基百科页面,例如this one

很遗憾,BeautifulSoup 无法处理如此大的内容,它会截断页面。

【问题讨论】:

    标签: python html beautifulsoup large-files scrape


    【解决方案1】:

    我在beautifulsoup-where-are-you-putting-my-html 找到了使用 BeautifulSoup 的解决方案,因为我认为它比 lxml 更容易。

    您唯一需要做的就是安装:

    pip install html5lib
    

    并将其作为参数添加到 BeautifulSoup:

    soup = BeautifulSoup(htmlContent, 'html5lib')
    

    但是,如果您愿意,也可以使用 lxml,如下所示:

    import lxml.html
    
    doc = lxml.html.parse('https://en.wikipedia.org/wiki/Talk:Game_theory')
    

    【讨论】:

      【解决方案2】:

      我建议你获取 html 内容,然后将其传递给 BS:

      import requests
      from bs4 import BeautifulSoup
      
      r = requests.get('https://en.wikipedia.org/wiki/Talk:Game_theory')
      if r.ok:
        soup = BeautifulSoup(r.content)
        # get the div with links at the bottom of the page
        links_div = soup.find('div', id='catlinks')
        for a in links_div.find_all('a'):
          print a.text
      else:
        print r.status_code
      

      【讨论】:

      • 我做了完全相同的事情,但是没有'html5lib'参数,内容中没有id='catlinks'!
      • 在我的浏览器里有(
      • 我做了同样的事情。您认为这可能与 Python 版本(2.7)、OS(WIN 8)、...有关吗?我觉得跟浏览器没有关系,因为我查了BeautifulSoup.prettify生成的实际html代码,不完整。
      • 我可以确认我上面编写的代码在 Windows 7 中不起作用,但在使用 python 2.7 的 Linux 中起作用。奇怪..
      猜你喜欢
      相关资源
      最近更新 更多
      热门标签