You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup匹配指定文本模式并删除对应完整HTML标签

问题原因

你代码的核心问题是对BeautifulSoup的find_all()方法的参数逻辑理解有误:

  • 直接向find_all()传入正则表达式时,方法会匹配HTML标签的名称,而非标签内部的文本内容。你的写法相当于在查找标签名包含interesar:的元素,显然不存在这类标签,自然返回空列表。
  • 你的正则表达式写法可以优化,要匹配文本包含指定字符串不需要前后加.*,正则默认会检测字符串任意位置是否存在匹配项,写re.compile(r'interesar:')即可。

修正方案

你需要通过find_all()的string参数指定文本匹配规则,再获取对应文本所属的父标签进行删除:

from bs4 import BeautifulSoup
import requests
import re

url = "https://www.globi.site/sample/"
response = requests.get(url)
data = response.content
soup = BeautifulSoup(data, 'lxml')

article = soup.find(class_ = 'entry-content')
# 定义文本匹配规则
my_pattern = re.compile(r'interesar:')
# 找到所有内容匹配的文本节点
matched_texts = article.find_all(string=my_pattern)
# 去重存储需要删除的标签,避免同一标签下多个文本节点匹配导致重复操作
to_delete = set()
# 可选:指定你要删除的标签类型,避免误删内层行内标签
target_tags = {'p', 'h3', 'h4'}

for text in matched_texts:
    current_tag = text.parent
    # 向上查找直到找到目标类型的标签,不需要的话可以删掉这段循环直接用text.parent
    while current_tag.name not in target_tags and current_tag.parent != article:
        current_tag = current_tag.parent
    if current_tag.name in target_tags:
        to_delete.add(current_tag)

# 批量删除匹配标签
for tag in to_delete:
    tag.decompose()

print(article)

内容的提问来源于stack exchange,提问作者Catalin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 03:39:01