首页 > 解决方案 > 在 BS4 中按文本查找 HTML 标记

问题描述

假设我们有类似的 HTML 模式

<p class='cls1'> Hello </p>

所以我想通过使用BS4搜索“Hello”<p>来找到标签(我现在不知道文本周围有什么标签) 。

它应该像

full_string = soup.find(text=re.compile('Hello'))
full_string.get_parent_tag() # <p>
full_string.get_parent_class() # cls1

BS4可以吗?谢谢!

标签: pythonparsingweb-scrapingbeautifulsoup

解决方案


当然有可能。

import re

from bs4 import BeautifulSoup


your_html = """<p class='cls1'> Hello </p>"""
print(BeautifulSoup(your_html, "html.parser").find_all(lambda t: t.name == "p" and re.compile("Hello")))

输出:

[<p class="cls1"> Hello </p>]

如果您不知道要使用的标签,可以尝试以下操作:

from lxml import html


your_html = """<p class='cls1'> Hello </p>"""
print(html.fromstring(your_html).xpath("//*[contains(text(), 'Hello')]"))

输出:

[<Element p at 0x7f2b172ae5e0>]

推荐阅读