使用BeautifulSoup在两个h2标题之间获取文本
问题描述:
我想抓取在Description之后和Next Header之前的文本。使用BeautifulSoup在两个h2标题之间获取文本
我知道:
In [8]: soup.findAll('h2')[6]
Out[8]: <h2>Description</h2>
不过,我不知道怎么抢的实际文本。问题是我有多个链接来做到这一点。 一些有号码:
<h2>Description</h2>
<p>This is the text I want </p>
<p>This is the text I want</p>
<h2>Next header</h2>
但是,有些则没有:
> <h2>Description</h2>
> This is the text I want
>
> <h2>Next header</h2>
而且在每一个与p,我不能只是做soup.findAll( 'P') 22],因为在某些'p'是21或20.
答
检查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())
这有效,但抓取所有的文本,当我只需要它在两个头之间。我会尝试修改你给我的内容,看看它是否有效,谢谢! – user6754289