如何用匹配的字符串在另一个段落后面刮出一个段落



我想在另一个具有特定文本"Interested String ZZZ" 的段落后面抓取一个段落

例如:

<p align="center"><strong><span style="text-decoration: underline;">Interested String ZZZ</span></strong></p>
<p style="text-align: justify;"><span style="font-size: small;">This is the paragraph string that i want to scrape out</span></p>

我如何在python中做到这一点?

使用text参数根据元素的文本内容匹配元素,然后使用find_next_sibling()获得下一个<p>同级元素:

>>> from bs4 import BeautifulSoup
>>> raw = '''<div>
... <p align="center"><strong><span style="text-decoration: underline;">Interested String ZZZ</span></strong></p>
... <p style="text-align: justify;"><span style="font-size: small;">This is the paragraph string that i want to scrape out</span></p>
... </div>'''
... 
>>> soup = BeautifulSoup(raw, "lxml")
>>> [s.find_next_sibling("p").string for s in soup("p", text="Interested String ZZZ")]
[u'This is the paragraph string that i want to scrape out']

相关内容

最新更新