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

解决BeautifulSoup无法提取text1中含‘View Sport’的a标签href问题

问题

需要提取text1和text2中,包含文本“View Sport”的<span>所在<a>标签的href属性值,目标URL分别为https://sports.atlas.com/rugby(来自text1)和https://sport.atlas/football(来自text2)。现有代码可提取text2的URL,但无法提取text1的。

原因分析
  1. HTML结构错误:text1中的<span>标签未正确闭合(代码中写为<span>View Sport<span>,缺少闭合的</span>),导致BeautifulSoup解析时DOM结构错乱,原选择器无法匹配到目标元素。
  2. 选择器局限性:原选择器a > span要求<span>是<a>的直接子元素,一旦解析后的结构不符合该层级关系,就会匹配失败。
  3. 变量未定义:原代码中soup = BeautifulSoup(text, 'html.parser')里的text变量未定义,需替换为text1或text2才能分别处理对应文本。
解决方案

1. 修复HTML结构

先预处理text1,补全未闭合的<span>标签:

text1 = text1.replace("<span>View Sport<span>", "<span>View Sport</span>")

2. 改用更鲁棒的元素查找逻辑

放弃严格的直接子元素选择器,改为查找包含目标文本的<span>,再定位其父<a>标签:

from bs4 import BeautifulSoup
import re

# 处理text1
text1 = text1.replace("<span>View Sport<span>", "<span>View Sport</span>")
soup1 = BeautifulSoup(text1, 'html.parser')
target_span1 = soup1.find("span", string=re.compile(r"\s*View Sport\s*"))
if target_span1 and target_span1.parent.name == "a":
    print(target_span1.parent["href"])  # 输出:https://sports.atlas.com/rugby

# 处理text2
soup2 = BeautifulSoup(text2, 'html.parser')
target_span2 = soup2.find("span", string=re.compile(r"\s*View Sport\s*"))
if target_span2 and target_span2.parent.name == "a":
    print(target_span2.parent["href"])  # 输出:https://sport.atlas/football

3. 优化匹配逻辑(可选)

如果文本中存在多余的空格、换行,正则表达式中加入\s*可以忽略这些空白字符,提升匹配成功率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:54:58