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

如何在Python的BeautifulSoup4中选择多类元素并处理None值错误?

Fixing AttributeError and None Comparison Issue in Web Scraping

Let's break down the issues in your code and fix them step by step:

Key Problems Identified

  1. AttributeError When Element Doesn't Exist: When product_item.find('span', class_='food_price on_sale') can't locate the target element, it returns None. You tried to access .text directly on this None value, which triggers the AttributeError you're seeing.
  2. Incorrect None Comparison: You used if price_sale == 'None' — this compares the None object to the string literal 'None', which will never evaluate to true. In Python, the correct way to check for None is using is None.

Corrected Code

# First, retrieve the element without immediately accessing its text
price_sale_element = product_item.find('span', class_='food_price on_sale')

if price_sale_element is None:
    # Set to -1 when the target element doesn't exist
    price_sale = -1
else:
    # Extract text when the element is found
    price_sale = price_sale_element.text

# Optional: Add fallback for price_price to avoid potential errors
price_price_element = product_item.find('span', class_='food_price')
price_price = price_price_element.text if price_price_element else "No price available"

print(price_sale)

Explanation

  • We first get the element object (price_sale_element) instead of directly calling .text, which prevents the AttributeError when the element is missing.
  • Using if price_sale_element is None correctly checks for the absence of the element — this is the standard Python way to compare against None.
  • For price_price, we added a fallback value ("No price available") to handle cases where that element might also be missing, avoiding another possible error.

This code will properly handle both of your scenarios:

  • In the first scenario, it will extract the text $45 from the span.food_price.on_sale element.
  • In the second scenario, since the target element doesn't exist, price_sale will be set to -1.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:50:48