[英]Catch Exception , Run Alternative Code & Continue from Line Python
我目前正在使用Selenium和BeautifulSoup来提取数据,有时候不同页面的格式可能略有不同,最多3种不同类型的html差异,当它来到不同的页面之一时,我无法帮助它它给了我一个例外,因为数据不存在。
我可以执行类似Exception = AttributeError的操作,尝试此代码并从停止的位置继续吗?
AttributeError: 'NoneType' object has no attribute 'text'
这是当前的代码
price = soup.find('li', {'id' :'J_PromoPrice'})
priced = price.find('strong', {'class' :'tb-rmb-num'}).text
if priced == "":
priced = price.find('strong', {'class' :'tb-rmb-num'}).text
else:
print ("No Normal Price Found")
正如你所看到的,已经存在一组IF ELSE来检测它是否为空,如果为空=找到另一个标签用于处理2种不同类型的html的文本,但是第3个我正面临问题的是它没有甚至没有TAG,但确实有它在其他地方。
简而言之,我正试图从其他地方获取文本,如果我点击此异常然后继续脚本从异常被打在我脸上。
更新完整跟踪
Traceback (most recent call last):
File "C:\Users\X\Desktop\Python\python.py", line 521, in <module>
getLoadItem()
File "C:\Users\X\Desktop\Python\python.py", line 57, in getLoadItem
getLoadItemAnalyse(loop['ID'],loop['Link'])
File "C:\Users\X\Desktop\Python\python.py", line 236, in getLoadItemAnalyse
priced = price.find('strong', {'class' :'tb-rmb-num'}).text
AttributeError: 'NoneType' object has no attribute 'text'
您可以使用try/except
块。
例如:
price = soup.find('li', {'id' :'J_PromoPrice'})
try:
priced = price.find('strong', {'class' :'tb-rmb-num'}).text
if priced == "":
priced = price.find('strong', {'class' :'tb-rmb-num'}).text
else:
print ("No Normal Price Found")
except AttributeError:
# Try this code instead
这基本上意味着,“好的尝试这个代码,它可能会搞砸”,在这种情况下,在catch
块下面做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.