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

Python如何用BeautifulSoup获取两个span标签间a标签的href属性

提取指定span标签内a标签href属性的实现方案

前置准备

如果尚未安装相关依赖,执行以下命令安装:
pip install beautifulsoup4 lxml

基础实现代码

from bs4 import BeautifulSoup

# 替换为你的实际HTML内容,此处用示例结构演示
html_content = '''
<span class="mentioned">
<a class="mentioned-123" onclick="information('123');" href="#28669">&gt;&gt;28669</a>
</span>
'''

# 初始化HTML解析对象
soup = BeautifulSoup(html_content, 'lxml')

# 第一步:定位class为mentioned的span标签
target_span = soup.find('span', class_='mentioned')
# 第二步:在span内部查找a标签
target_a = target_span.find('a')
# 第三步:提取href属性值
# get方法在属性不存在时返回None不会报错,也可以直接用target_a['href']取值
href_value = target_a.get('href')

print(href_value) # 输出结果:#28669

简化写法:使用CSS选择器

可以一步直接定位到目标a标签,代码更简洁:

target_a = soup.select_one('span.mentioned a')
href_value = target_a.get('href')

异常兼容建议

如果不确定目标标签一定存在,建议加非空判断避免抛出异常:

target_a = soup.select_one('span.mentioned a')
if target_a:
    href_value = target_a.get('href')
    print(href_value)
else:
    print("未匹配到目标a标签")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:45:08