如何在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
- AttributeError When Element Doesn't Exist: When
product_item.find('span', class_='food_price on_sale')can't locate the target element, it returnsNone. You tried to access.textdirectly on thisNonevalue, which triggers theAttributeErroryou're seeing. - Incorrect None Comparison: You used
if price_sale == 'None'— this compares theNoneobject to the string literal'None', which will never evaluate to true. In Python, the correct way to check forNoneis usingis 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 theAttributeErrorwhen the element is missing. - Using
if price_sale_element is Nonecorrectly checks for the absence of the element — this is the standard Python way to compare againstNone. - 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
$45from thespan.food_price.on_saleelement. - In the second scenario, since the target element doesn't exist,
price_salewill be set to-1.
内容的提问来源于stack exchange,提问作者IgorAlves
相关产品推荐
相关产品推荐

