You need to enable JavaScript to run this app. Beautiful Soup提取指定class的div文本并实现相等匹配的正确写法
优惠活动
大模型
产品
解决方案
定价
更多

Beautiful Soup提取指定class的div文本并实现相等匹配的正确写法

问题根源

直接用原始div.text做相等判断不生效,是因为目标div内的文本前后带了大量缩进空格、换行符,未处理的提取结果会包含这些不可见字符,和你预设的精确匹配字符串存在字符级差异,最终判断必然返回False。

完整可运行代码实现
from bs4 import BeautifulSoup

# 替换为你实际的页面HTML加载逻辑
demo_html = '''<div class="c-capr-add__input-na">
                We're sorry. This product is not available online at this time.
            </div>'''

soup = BeautifulSoup(demo_html, "html.parser")
out_of_stock_divs = soup.find("div", class_="c-capr-add__input-na")

# 非空判断避免元素不存在触发报错
if out_of_stock_divs:
    raw_text = out_of_stock_divs.text
    # 做文本空白标准化:先清除首尾空白,再将内部连续的换行、多空格、制表符合并为单个空格
    clean_text = " ".join(raw_text.strip().split())
    # 此时即可正常实现你需要的相等判断逻辑
    return clean_text == "We're sorry. This product is not available online at this time."
常见踩坑提醒
  • 禁止直接使用未处理的.text返回值做精确比对:原始提取结果为" We're sorry. This product is not available online at this time. ",前后全是缩进空格,哪怕差一个字符,相等判断都会失效
  • 如果不需要严格全量匹配,也可以简化为包含判断,直接判断"We're sorry" in clean_text即可识别缺货状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.09 02:45:03