python - 在 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可以吗?谢谢!
解决方案
当然有可能。
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>]
推荐阅读
- ios - 苹果一直拒绝我们的应用,因为他们声称它使用了 HealthKit?
- java - Spring Cloud 版本变更后,无法构建标准Jar
- amazon-web-services - Azure 中的 AWS Transit Gateway 等效服务
- android - 为什么模拟器没有获得 FCM 推送
- node.js - 如何在没有网络的情况下安装 Node.js 包?
- android - 如何在谷歌地图android中捕获的多边形区域中添加标记
- jenkins - 如何在隔离的 pod 中为声明式 jenkins 管道运行并行阶段
- javascript - 使用 neo4j-javascript-driver 关闭会话的正确方法是什么?
- flutter - 如何在 iOS 模拟器上修复“A RenderFlex 在右侧溢出 1329 像素”
- c++ - 如何使用 C 中的内部 c++ 类类型?