python - 使用 BeautifulSoup 删除元素中的选定标签
问题描述
在一个页面中,我们有几个 h1。在第一个 h1 中,我想删除带有 class 的标签read-time
。这是我的尝试。但是,标签并未被删除。我哪里错了?
h1s = main.select('h1')
print("BEFORE: main.select('h1')", main.select('h1'))
real_h1 = h1s[0]
if real_h1.select('.read-time') is not None:
real_h1.select('.read-time').clear()
print("AFTER: main.select('h1')", main.select('h1'))
日志
BEFORE: main.select('h1') [<h1>Introduction<span class="read-time"><span class="minutes"></span> min read</span></h1>, <h1 id="before-you-begin">Before You Begin</h1>]
AFTER: main.select('h1') [<h1>Introduction<span class="read-time"><span class="minutes"></span> min read</span></h1>, <h1 id="before-you-begin">Before You Begin</h1>]
解决方案
使用 decompose() 删除。
html='''<h1>Introduction<span class="read-time"><span class="minutes"></span> min read</span></h1>, <h1 id="before-you-begin">Before You Begin</h1>]'''
main=BeautifulSoup(html,'html.parser')
h1s = main.select('h1')
print("BEFORE: main.select('h1')", main.select('h1'))
real_h1 = h1s[0]
if real_h1.select('.read-time') is not None:
real_h1.decompose()
print("AFTER: main.select('h1')", main.select('h1'))
输出:
BEFORE: main.select('h1') [<h1>Introduction<span class="read-time"><span class="minutes"></span> min read</span></h1>, <h1 id="before-you-begin">Before You Begin</h1>]
AFTER: main.select('h1') [<h1 id="before-you-begin">Before You Begin</h1>]
推荐阅读
- azure - Azure 流分析处理/路由来自同一设备的不同大小和内容的 IoT 消息的推荐方法是什么
- amazon-cloudformation - 预填充的可用区选项列表作为 cloudformation 模板的参数
- docker - 无法使用 docker pull 从 okd/openshift-origin docker 注册表匿名拉取图像
- django - 如何更新模型查询
- sql - 将本地 mssql/stored-procs(a lot)/C# 应用程序迁移到 AWS 环境的最佳方法是什么?
- canvas - HTML5 Canvas/CreateJS 停止所有嵌套的影片剪辑?
- google-cloud-platform - 托管在 Google Cloud Run 中的 Node Express REST
- powershell - powershell -NonInteractive -ExecutionPolicy 绕过 -Command
- list - 如何删除/调整列表中的分隔符?
- android - 使用 Play Services Location API 获取周边地点