[英]Catch Exception , Run Alternative Code & Continue from Line Python
I'm currently using Selenium & BeautifulSoup to extract data , sometimes the format for different pages might be slightly different, at most max 3 different type of html difference, when it came to one of the different page, i couldn't help it as it gave me an exception because the data isnt there. 我目前正在使用Selenium和BeautifulSoup来提取数据,有时候不同页面的格式可能略有不同,最多3种不同类型的html差异,当它来到不同的页面之一时,我无法帮助它它给了我一个例外,因为数据不存在。
Can i do something like if Exception = AttributeError, try this code and continue from where it stopped? 我可以执行类似Exception = AttributeError的操作,尝试此代码并从停止的位置继续吗?
AttributeError: 'NoneType' object has no attribute 'text'
This is the current code 这是当前的代码
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")
As you can see , there is already a set of IF ELSE to detect if it's empty , if empty = find another tag for text that will handle 2 different type of html but the 3rd one which i'm facing an issue is that it doesn't even have the TAG but it does have it somewhere else. 正如你所看到的,已经存在一组IF ELSE来检测它是否为空,如果为空=找到另一个标签用于处理2种不同类型的html的文本,但是第3个我正面临问题的是它没有甚至没有TAG,但确实有它在其他地方。
In short, i'm trying to Grab text from somewhere else if i hit this exception then continue the script from where the exception was slapped in my face. 简而言之,我正试图从其他地方获取文本,如果我点击此异常然后继续脚本从异常被打在我脸上。
Update Full Trace 更新完整跟踪
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'
You can use a try/except
block. 您可以使用
try/except
块。
So for example: 例如:
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
This basically means, "Okay try this code, and it might mess up", in that case, do whats underneath the catch
block. 这基本上意味着,“好的尝试这个代码,它可能会搞砸”,在这种情况下,在
catch
块下面做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.