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

使用BeautifulSoup定位指定class的span标签返回None问题求助

问题解决:BeautifulSoup无法识别预订状态标签

问题原因

当前代码中使用soup.find('span', class_='status_tag approved')查找元素时,html.parser对多类名的解析存在兼容性问题,导致无法匹配到目标标签;同时直接用空格分隔类名的写法,会被部分解析逻辑识别为单一class值,而非同时包含两个class的元素。

修复方案

方案1:使用CSS选择器(推荐)

CSS选择器对多类名元素的匹配逻辑更精准,替换查找逻辑如下:

def check_booking_status(html_content):
    soup = BeautifulSoup(html_content, 'html.parser')
    # 用CSS选择器匹配同时拥有status_tag和approved类的span标签
    status_tag = soup.select_one('span.status_tag.approved')
    print(status_tag)
    return 'Approved' if status_tag else 'Not Approved'

方案2:拆分class条件查找

先定位所有带status_tag类的span标签,再检查是否包含approved类:

def check_booking_status(html_content):
    soup = BeautifulSoup(html_content, 'html.parser')
    # 先获取所有带status_tag类的span
    status_spans = soup.find_all('span', class_='status_tag')
    for span in status_spans:
        # 检查当前span是否包含approved类
        if 'approved' in span.get('class', []):
            print(span)
            return 'Approved'
    return 'Not Approved'

方案3:更换解析器(若上述方案无效)

html.parser功能有限,改用lxml解析器可提升HTML解析准确性,需先安装依赖:

pip install lxml

修改解析器参数:

soup = BeautifulSoup(html_content, 'lxml')

额外优化建议

可结合标签文本辅助验证(处理文本中的空格),避免类名变更导致的识别失败:

# 结合文本内容判断,增强鲁棒性
if span.get_text(strip=True) == 'Approved':
    return 'Approved'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:05:32