捕获异常,运行替代代码&;从Python行继续

捕获异常,运行替代代码&;从Python行继续,python,selenium,python-3.x,selenium-webdriver,beautifulsoup,Python,Selenium,Python 3.x,Selenium Webdriver,Beautifulsoup,我目前正在使用Selenium&BeautifulSoup提取数据,有时不同页面的格式可能会略有不同,最多3种不同类型的html差异,当涉及到不同页面时,我无能为力,因为它给了我一个例外,因为数据不存在 我是否可以执行类似于if Exception=AttributeError的操作,尝试此代码并从停止的位置继续? AttributeError: 'NoneType' object has no attribute 'text' 这是当前代码 price = soup.find('li',

我目前正在使用Selenium&BeautifulSoup提取数据,有时不同页面的格式可能会略有不同,最多3种不同类型的html差异,当涉及到不同页面时,我无能为力,因为它给了我一个例外,因为数据不存在

我是否可以执行类似于if 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来检测它是否为空,IF-empty=为文本查找另一个标记,该标记将处理2种不同类型的html,但我面临的第三个问题是,它甚至没有标记,但它确实在其他地方有标记

简而言之,我试图从其他地方抓取文本,如果我点击了这个异常,然后从异常打到我脸上的地方继续脚本

更新完整跟踪

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'
回溯(最近一次呼叫最后一次):
文件“C:\Users\X\Desktop\Python\Python.py”,第521行,在
getLoadItem()
getLoadItem中第57行的文件“C:\Users\X\Desktop\Python\Python.py”
GetLoadItemAnalysis(循环['ID'],循环['Link'])
文件“C:\Users\X\Desktop\Python\Python.py”,第236行,位于GetLoadItemAnalysis中
priced=price.find('strong',{'class':'tb-rmb-num'})。文本
AttributeError:“非类型”对象没有属性“文本”

您可以使用
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
块下面的事情。

你能给我们完整的回溯吗?@GamesBrainiac完成了谢谢!检查我的解决方案是否适用于您。在它运行catch之后,它还会继续运行下面的代码吗?下面还有很多代码,绝对会的。如果这个解决方案对你有效的话。请投票并接受答案。是的,谢谢!顺便说一句,这是一个尝试,除了,catch不起作用,我做了一个编辑,希望这对其他人有用:)