【问题标题】:Using BeautifulSoup to parse multiple layers使用 BeautifulSoup 解析多层
【发布时间】:2014-05-12 17:59:04
【问题描述】:

我有一个保存为 .htm 的网页。本质上,我需要解析 6 层 div 并从中获取特定数据,我对如何处理这个问题感到很困惑。我尝试了不同的技术,但没有任何效果。

HTM 文件有一堆标签,但有一个看起来像这样的 div:

<div id="fbbuzzresult" class.....>
   <div class="postbuzz"> .... </div>
      <div class="linkbuzz">...</div>
      <div class="descriptionbuzz">...</div>
      <div class="metabuzz>
         <div class="time">...</div>
      <div>
   <div class="postbuzz"> .... </div>
   <div class="postbuzz"> .... </div>
   <div class="postbuzz"> .... </div>
</div>

我目前正在尝试 BeautifulSoup。更多上下文...

  1. 整个文件中只有一个 fbbuzzresult
  2. fbbuzzresult 中有多个 postbuzz
  3. postbuzz 中有如上所示的 div

我需要在 each postbuzz div 中提取并打印上面显示的每个内容。

非常感谢您对一些框架代码的帮助和指导! P.S - 忽略 div 类中的破折号。 谢谢!

【问题讨论】:

标签: python html beautifulsoup extract


【解决方案1】:

你应该能够像你的父母soup一样使用你的结果:

from BeautifulSoup import BeautifulSoup as bs
soup = bs(html)
div = soup.find("div",{"id":"fbbuzzresult"})
post_buzz = div.findAll("div",{"class":"postbuzz"})

但我在这样做之前遇到了错误,所以作为辅助方法,你可以只做一种sub_soup

from BeautifulSoup import BeautifulSoup as bs
soup = bs(html)
div = soup.find("div",{"id":"fbbuzzresult"})
sub_soup = bs(str(div))
post_buzz = sub_soup.findAll("div",{"class":"postbuzz"})

【讨论】:

    【解决方案2】:

    首先阅读 BeautifulSoup 文档http://www.crummy.com/software/BeautifulSoup/bs4/doc/

    其次,这里有一个小例子可以帮助你:

    from bs4 import BeautifulSoup as bs
    
    soup = bs(your_html_content)
    
    # for fbbuzzresult
    buzz = soup.findAll("div", {"id" : "fbbuzzresult"})[0]
    
    # to get postbuzz
    pbuzz = buzz.findAll("div", {"class" : "postbuzz"})
    
    """pbuzz is now an array with the postbuzz divs
       so now you can iterate through them, get
       the contents, keep traversing the DOM with BS 
       or do whatever you are trying to do
    
       So say you want the text from an element, you
       would just do: the_element.contents[0]. However
       if I'm remembering correctly you have to traverse 
       down through all of it's children to get the text.
    """
    

    【讨论】:

      猜你喜欢
      • 2017-11-01
      • 2013-09-30
      • 2013-03-10
      • 1970-01-01
      • 2018-07-13
      • 2014-05-19
      • 1970-01-01
      • 2013-03-20
      • 2017-08-21
      相关资源
      最近更新 更多