如何将一个段落与另一个带有匹配字符串的段落连在一起?

2024-04-26 01:09:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在另一个段落后面找一个段落,后面有一个特定的文本"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中如何做到这一点?你知道吗


Tags: text文本stringstylestrong段落centerspan
1条回答
网友
1楼 · 发布于 2024-04-26 01:09:20

使用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']

相关问题 更多 >