使用BeautifulSoup在两个h2标头之间获取文本

use*_*289 2 python beautifulsoup

我想获取“描述”之后和“下一个标题”之前的文本。

我知道:

In [8]: soup.findAll('h2')[6]
Out[8]: <h2>Description</h2>
Run Code Online (Sandbox Code Playgroud)

但是,我不知道如何获取实际文本。问题是我有多个链接可以执行此操作。有些具有p:

                                         <h2>Description</h2>

  <p>This is the text I want </p>
<p>This is the text I want</p>   
                                        <h2>Next header</h2>
Run Code Online (Sandbox Code Playgroud)

但是,有些不这样做:

>                                       <h2>Description</h2>
>                        This is the text I want                 
> 
>                                       <h2>Next header</h2>
Run Code Online (Sandbox Code Playgroud)

同样在每个带有p的人上,我不能只做soup.findAll('p')[22],因为在某些情况下,'p'是21或20。

Zro*_*roq 6

检查NavigableString以检查下一个兄弟姐妹是否是文本节点,或者Tag检查它是否是元素。

如果下一个兄弟是标头,请中断循环。

from bs4 import BeautifulSoup, NavigableString, Tag
import requests

example = """<h2>Description</h2><p>This is the text I want </p><p>This is the text I want</p><h2>Next header</h2>"""

soup = BeautifulSoup(example, 'html.parser')
for header in soup.find_all('h2'):
    nextNode = header
    while True:
        nextNode = nextNode.nextSibling
        if nextNode is None:
            break
        if isinstance(nextNode, NavigableString):
            print (nextNode.strip())
        if isinstance(nextNode, Tag):
            if nextNode.name == "h2":
                break
            print (nextNode.get_text(strip=True).strip())
Run Code Online (Sandbox Code Playgroud)