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
相关产品推荐
相关产品推荐

