我正在尝试在以下代码中使用两个except:

try:
    Contributions = driver.find_element_by_xpath('//*[@id="_ctl0"]/table[2]/tbody/tr[2]/td[2]/table[5]/tbody/tr[5]/td[2]/span').text
    Expenditures = driver.find_element_by_xpath('//*[@id="_ctl0"]/table[2]/tbody/tr[2]/td[2]/table[5]/tbody/tr[7]/td[2]/span').text

except NoSuchElementException:
    Contributions = driver.find_element_by_xpath('//*[@id="_ctl0"]/table[2]/tbody/tr[2]/td[2]/table[4]/tbody/tr[5]/td[2]/span').text
    Expenditures = driver.find_element_by_xpath('//*[@id="_ctl0"]/table[2]/tbody/tr[2]/td[2]/table[4]/tbody/tr[7]/td[2]/span').text

except NoSuchElementException:
    Contributions = None
    Expenditures = None

我收到的错误消息如下:
#First Error
NoSuchElementException                    Traceback (most recent call last)

#Second Error
During handling of the above exception, another exception occurred:
NoSuchElementException                    Traceback (most recent call last)

#Third Error
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="_ctl0"]/table[2]/tbody/tr[2]/td[2]/table[4]/tbody/tr[5]/td[2]/span"}
  (Session info: chrome=83.0.4103.97)



由于某种原因,代码会卡在第二个除外上,而不会尝试第三个除外。

如果在第二个异常之后找不到元素,我只想用缺少的填充ContributionsExpenditures并让代码通过。

最佳答案

您需要嵌套try/except块。

try:
    Contributions = driver.find_element_by_xpath('//*[@id="_ctl0"]/table[2]/tbody/tr[2]/td[2]/table[5]/tbody/tr[5]/td[2]/span').text
    Expenditures = driver.find_element_by_xpath('//*[@id="_ctl0"]/table[2]/tbody/tr[2]/td[2]/table[5]/tbody/tr[7]/td[2]/span').text

except NoSuchElementException:
    try:
        Contributions = driver.find_element_by_xpath('//*[@id="_ctl0"]/table[2]/tbody/tr[2]/td[2]/table[4]/tbody/tr[5]/td[2]/span').text
        Expenditures = driver.find_element_by_xpath('//*[@id="_ctl0"]/table[2]/tbody/tr[2]/td[2]/table[4]/tbody/tr[7]/td[2]/span').text

    except NoSuchElementException:
        Contributions = None
        Expenditures = None

关于python - python中的多个异常(exception),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62403374/

10-09 03:25