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

如何同时基于文本与href正则抓取网页元素并去重?

解决BeautifulSoup同时匹配文本与href正则/合并去重的方法

一、单次调用同时满足文本与href正则匹配

直接给find_all传入自定义判断函数,同时校验文本和href的正则规则:

import re
from bs4 import BeautifulSoup

# 定义正则规则
text_pattern = re.compile(r'目标文本正则')
href_pattern = re.compile(r'目标链接正则')

def match_conditions(tag):
    # 根据需求调整目标标签类型,这里以a标签为例
    if tag.name != 'a':
        return False
    # 校验href属性
    href_match = href_pattern.search(tag.get('href', ''))
    # 校验文本内容(strip=True去除多余空格避免匹配失败)
    text_match = text_pattern.search(tag.get_text(strip=True))
    # 两个条件同时满足才返回True
    return href_match and text_match

# 执行抓取
soup = BeautifulSoup(html_content, 'html.parser')
result = soup.find_all(match_conditions)

二、两次调用后合并去重

先分别按两种规则抓取,再通过元素特性或唯一属性去重:

方法1:利用元素哈希值直接去重

BeautifulSoup的Tag对象支持哈希,可通过字典快速去重:

# 分别抓取文本匹配的标签(注意text匹配返回NavigableString,需取对应父标签)
text_matches = soup.find_all(text=text_pattern)
text_tags = [tag.parent for tag in text_matches if tag.parent.name == 'a']
# 抓取href匹配的标签
href_tags = soup.find_all('a', href=href_pattern)

# 合并并去重
unique_tags = list({tag: None for tag in text_tags + href_tags}.keys())

方法2:利用标签唯一属性去重

如果标签有唯一标识(比如href),用字典存储更可控:

tag_dict = {}
# 先存入文本匹配的标签
for tag in text_tags:
    href = tag.get('href')
    if href:
        tag_dict[href] = tag
# 存入href匹配的标签,重复href会自动覆盖
for tag in href_tags:
    href = tag.get('href')
    if href:
        tag_dict[href] = tag

# 去重后的结果
unique_tags = list(tag_dict.values())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:20:39