使用BeautifulSoup解析多层结构

0 投票
2 回答
3352 浏览
提问于 2025-04-18 06:19

我有一个保存为 .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。

我需要从每个 postbuzz 的 div 中提取并打印出上面提到的每一项。

非常感谢你的帮助和指导,能给我一些基础代码的框架就好了!
附注:忽略 div 类名中的短横线。
谢谢!

2 个回答

1

首先,先去看看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.
"""
3

你可以像使用你之前的 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"})

撰写回答