You need to enable JavaScript to run this app. Python中使用BeautifulSoup如何从匹配文本获取对应标签及属性
优惠活动
大模型
产品
解决方案
定价
更多

Python中使用BeautifulSoup如何从匹配文本获取对应标签及属性

解决BeautifulSoup根据标签文本获取对应标签名及属性的问题

需求说明

需要从HTML文本中根据标签内的文本内容,匹配获取对应标签名和属性值。

示例HTML代码

<a _sp="p2481888.m1379.l3250" href="https://www.ebay.com/b/Electronics/bn_7000259124">Electronics</a>

目标是获取文本为Electronics的对应标签名a,以及属性_sp的值p2481888.m1379.l3250。

现有代码

from bs4 import BeautifulSoup
import requests

Source = input("Enter the source: ")
Request = requests.get(Source, headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59"})
Soup = BeautifulSoup(Request.text, "html.parser")

Target = Soup.find_all(text="Electronics")

print(Target)

问题截图

问题图示

调整方案

现有代码返回的是匹配到的文本节点本身,要获取包裹该文本的标签对象,只需要访问文本节点的parent属性即可,之后就能直接读取标签名和对应属性值,调整后代码如下:

from bs4 import BeautifulSoup
import requests

source = input("Enter the source: ")
request = requests.get(source, headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59"})
soup = BeautifulSoup(request.text, "html.parser")

# 查找所有匹配文本的节点
text_nodes = soup.find_all(text="Electronics")

for node in text_nodes:
    # 获取对应标签对象
    target_tag = node.parent
    # 输出标签名
    print(f"对应标签名:{target_tag.name}")
    # 输出_sp属性值
    if "_sp" in target_tag.attrs:
        print(f"_sp属性值:{target_tag['_sp']}")

如果匹配的文本存在前后空格、需要模糊匹配的场景,可以把查找条件替换为:

text_nodes = soup.find_all(text=lambda t: t and "Electronics" in t.strip())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 09:15:00