如何检查网页price元素是否存在,避免Python爬虫报错?
解决爬虫中价格标签不存在的异常处理问题
直接通过find()获取标签时,若目标元素不存在会返回None,调用None.text就会触发AttributeError。你可以通过两步检查来避免这个问题,同时处理请求过程中的其他异常,保证循环持续运行:
修改后的代码示例
from bs4 import BeautifulSoup import requests # 替换成你的目标URL列表 target_urls = ["https://example.com/page1", "https://example.com/page2"] for url in target_urls: try: # 发送请求并检查响应状态 resp = requests.get(url) resp.raise_for_status() soup = BeautifulSoup(resp.text, "html.parser") # 先检查cost-box节点是否存在 cost_box = soup.find("div", class_="cost-box") if cost_box: # 再检查price标签是否存在 price_tag = cost_box.find("price") price = price_tag.text.strip() if price_tag else "invalid" else: # 连cost-box都不存在的情况也标记为invalid price = "invalid" print(f"页面 {url} 价格: {price}") except requests.exceptions.RequestException as e: # 捕获网络请求类错误,比如连接失败、404等 print(f"请求页面 {url} 出错: {str(e)}") price = "invalid"
关键处理逻辑
- 先判断
cost_box是否存在:soup.find()找不到元素时返回None,直接用if cost_box就能判断是否获取到了目标节点 - 对
price标签做二次检查:用三元表达式简化判断,存在则提取文本,否则赋值为"invalid" - 外层加
try-except捕获请求异常:避免网络问题导致程序中断,统一处理为"invalid"
内容的提问来源于stack exchange,提问作者DC37
相关产品推荐
相关产品推荐

