Python Bsoup4提取未被父元素包装的子元素 上下文

Python Bsoup4提取未被父元素包装的子元素 上下文,python,html,web-scraping,beautifulsoup,Python,Html,Web Scraping,Beautifulsoup,本文假设以下上下文: python 2.7 B组4 使用非包裹(相邻)元素刮取内容 问题 目标 Trevor希望提取页面内容,其中相关内容不由统一元素包装,而是与标题元素相邻 在下面的示例中,Trevor需要一个包含四个元素的python数据结构,每个元素包含一个“header”名称-值对和一个“body”名称-值对 细节 最好的解释方式是举例说明: <h2>Alpha blurb</h2> * content here one * content here t

本文假设以下上下文:

  • python 2.7
  • B组4
  • 使用非包裹(相邻)元素刮取内容
问题 目标
  • Trevor希望提取页面内容,其中相关内容不由统一元素包装,而是与标题元素相邻
  • 在下面的示例中,Trevor需要一个包含四个元素的python数据结构,每个元素包含一个“header”名称-值对和一个“body”名称-值对
细节 最好的解释方式是举例说明:

<h2>Alpha blurb</h2>

* content here one
* content here two

<h2>Bravo blurb</h2>

* content here one
* content here two
* content here tree
* content here four
* content here fyve
* content here seeks

<h2>Charlie blurb</h2>

* content here four
* content here fyve
* content here seeks

<h2>Delta blurb</h2>

* blah
Alpha模糊
*内容在这里
*这里的内容有两个
好极了
*内容在这里
*这里的内容有两个
*目录树
*这里的内容有四个
*内容在此fyve
*这里的内容寻求
查理宣传片
*这里的内容有四个
*内容在此fyve
*这里的内容寻求
三角洲宣传片
*废话
从Trevor到目前为止所看到的情况来看,Bsoup使用了一种抓取内容的策略,该策略包括查找容器元素并对其进行迭代和钻取

然而,在这个场景中,Trevor希望提取每个标题项及其关联的内容,即使关联的内容没有包装在包含元素中

一个内容节开始和另一个内容节结束的唯一指示是标题标记的位置

问题: 在bsoup4的文档中可以在哪里搜索,或者Trevor可以寻找什么术语来封装这一原理并获得他试图做的事情的结果?

Trevor需要在这里横着使用。例如:

from bs4 import BeautifulSoup


page = """
<div>
<h2>Alpha blurb</h2>

* content here one
* content here two

<h2>Bravo blurb</h2>

* content here one
* content here two
* content here tree
* content here four
* content here fyve
* content here seeks

<h2>Charlie blurb</h2>

* content here four
* content here fyve
* content here seeks

<h2>Delta blurb</h2>

* blah
</div>
"""
soup = BeautifulSoup(page)

for h2 in soup.find_all("h2"):

    print h2.text

    # loop over siblings until h2 is met (or no more siblings left)
    for item in h2.next_siblings:
        if item.name == "h2":
            break

        print item.strip()

    print "----"
我在想象问这个问题
Alpha blurb
* content here one
* content here two
----
Bravo blurb
* content here one
* content here two
* content here tree
* content here four
* content here fyve
* content here seeks
----
Charlie blurb
* content here four
* content here fyve
* content here seeks
----
Delta blurb
* blah
----