Python中第二个异常未生效?新手技术问题咨询
问题描述
我是Python新手,编写了如下爬虫代码,设置了TypeError和AttributeError两个异常捕获分支,预期触发异常后最终返回"None"。但实际运行时第二个异常未执行,报错显示在处理TypeError时又触发AttributeError,疑惑是否因循环或缩进导致该问题?
爬虫代码
import requests from bs4 import BeautifulSoup headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36' } for x in range(60,61): url = 'https://example.com/page/' r = requests.get(url+str(x), headers = headers) soup = BeautifulSoup(r.content, features='lxml') articles = soup.find_all('article', class_='blog-view') for item in articles: title = item.find('h2', class_="entry-title").text if title == "Premium" or title == "Deleted" or title == "deleted": image_url = "None" else: try: image_url = item.find('div', class_='entry-content').p.img['src'] except TypeError: image_url = item.find('div', class_='wp-caption').img['src'] except AttributeError: image_url = "None" print(image_url)
报错输出
TypeError Cell In [10], line 30 29 try: ---> 30 image_url = item.find('div', class_='entry-content').p.img['src'] 31 except TypeError: TypeError: 'NoneType' object is not subscriptable During handling of the above exception, another exception occurred: AttributeError Cell In [10], line 32 30 image_url = item.find('div', class_='entry-content').p.img['src'] 31 except TypeError: ---> 32 image_url = item.find('div', class_='wp-caption').img['src'] 33 except AttributeError: 34 image_url = "None" AttributeError: 'NoneType' object has no attribute 'img'
问题原因
不是循环或缩进的问题,核心原因是:except TypeError分支内的代码抛出了新的AttributeError,这个异常不在当前try-except块的处理范围内。
当第一个try块触发TypeError后,程序进入except TypeError分支执行代码,但这段代码里item.find('div', class_='wp-caption')返回了None,接着访问.img就会抛出AttributeError,而当前try-except的except AttributeError只负责处理try块内的异常,不会处理其他except分支里的异常,所以程序直接报错退出。
解决方法
方法一:给except TypeError分支添加嵌套try-except
把第二个查找逻辑也放进异常保护里:
try: image_url = item.find('div', class_='entry-content').p.img['src'] except TypeError: try: image_url = item.find('div', class_='wp-caption').img['src'] except AttributeError: image_url = "None" except AttributeError: image_url = "None"
方法二:拆分链式调用,提前判断节点是否存在
避免直接链式调用find().p.img['src'],先逐个判断节点是否存在,从根源上减少异常:
entry_content = item.find('div', class_='entry-content') if entry_content and entry_content.p and entry_content.p.img: image_url = entry_content.p.img['src'] else: wp_caption = item.find('div', class_='wp-caption') if wp_caption and wp_caption.img: image_url = wp_caption.img['src'] else: image_url = "None"
方法三:合并异常捕获,简化逻辑
直接捕获所有可能的异常,同时调整查找逻辑的顺序:
try: # 先尝试第一个选择器路径 img_tag = item.find('div', class_='entry-content').p.find('img') if img_tag: image_url = img_tag['src'] else: # 第一个路径找不到img,尝试第二个选择器 img_tag = item.find('div', class_='wp-caption').find('img') image_url = img_tag['src'] except (TypeError, AttributeError): image_url = "None"
内容的提问来源于stack exchange,提问作者Vardhan
相关产品推荐
相关产品推荐

