【发布时间】:2020-10-05 18:13:35
【问题描述】:
我正在尝试在以下代码中使用两个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)
由于某种原因,代码卡在第二个 except 上,没有尝试第三个 except。
如果在第二个异常之后找不到元素,我只想将Contributions和Expenditures填上missing,让代码通过。
【问题讨论】:
-
感谢大家的帮助!非常感谢!
标签: python web-scraping error-handling try-except