Python网页爬虫如何用try-except处理缺失元素,未找到时返回“不可用”
问题原因
- 你没有在每次循环遍历商品的时候预先初始化
actual_price变量,当某个商品找不到原价触发异常时,actual_price会复用前一次循环的旧值,才会出现错误沿用前一个商品35原价的问题。 - 异常分支只打印了提示,没有主动给
actual_price赋值为“不可用”,后续打印时自然无法输出预期的默认值。 - 原代码中headers的定义格式错误、容器查询漏写class键,也可能导致后续元素查找异常。
修复方案
- 每次循环开始时先给
actual_price设置默认值“不可用”,避免变量残留 - 异常分支不需要额外操作,维持默认值即可,也可以按需保留提示
- 修正参数格式错误,保证元素查找逻辑正确
修复后完整代码
from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq import bs4 # 修正headers格式,补充User-Agent键 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Brave Chrome/83.0.4103.116 Safari/537.36'} my_url = 'https://www.jiomart.com/c/groceries/dairy-bakery/dairy/62' uclient = uReq(my_url) page_html = uclient.read() uclient.close() bs41 = soup(page_html, 'html.parser') # 修正容器查询参数,补充class键 containers = bs41.find_all('div', {'class': 'col-md-3 p-0'}) for container in containers: # 循环开始先初始化actual_price为默认值,避免残留上一次循环的结果 actual_price = "不可用" p_name = container.find_all('span', {'class' : 'clsgetname'}) productname = p_name[0].text o_p = container.find_all('span' , id = 'final_price' ) offer_price = o_p[0].text try: ap = container.find_all('strike', id = 'price') actual_price = ap[0].text except: # 触发异常时不需要额外操作,维持默认值即可,也可自行添加打印提示 pass print('Product name is', productname) print('Product Mrp is', offer_price) print('Product actual price', actual_price) print()
内容的提问来源于stack exchange,提问作者Bhavya Lodaya
相关产品推荐
相关产品推荐

