一尘不染

pythonseleniumwebscraping“ NoSuchElementException”无法识别

selenium

有时,我会在页面上寻找可能存在或不存在的元素。我想用/尝试/捕获这种情况,NoSuchElementException当某些HTML元素不存在时,selenium会抛出该异常。原始例外:

NoSuchElementException: Message: u'Unable to locate element: {"method":"css selector","selector":"#one"}' ; Stacktrace: 
    at FirefoxDriver.prototype.findElementInternal_ (file:///var/folders/6q/7xcjtgyj32nfc2yp_y5tr9pm0000gn/T/tmp63Mz2a/extensions/fxdriver@googlecode.com/components/driver_component.js:8899)
    at FirefoxDriver.prototype.findChildElement (file:///var/folders/6q/7xcjtgyj32nfc2yp_y5tr9pm0000gn/T/tmp63Mz2a/extensions/fxdriver@googlecode.com/components/driver_component.js:8911)
    at DelayedCommand.prototype.executeInternal_/h (file:///var/folders/6q/7xcjtgyj32nfc2yp_y5tr9pm0000gn/T/tmp63Mz2a/extensions/fxdriver@googlecode.com/components/command_processor.js:10840)
    at DelayedCommand.prototype.executeInternal_ (file:///var/folders/6q/7xcjtgyj32nfc2yp_y5tr9pm0000gn/T/tmp63Mz2a/extensions/fxdriver@googlecode.com/components/command_processor.js:10845)
    at DelayedCommand.prototype.execute/< (file:///var/folders/6q/7xcjtgyj32nfc2yp_y5tr9pm0000gn/T/tmp63Mz2a/extensions/fxdriver@googlecode.com/components/command_processor.js:10787)

具有讽刺意味的是,它不会让我捕捉到之前抛出的异常吗?代码在这里:

elt = driver.find_element_by_css_selector('.information')
try:
    dat1 = elt.find_element_by_css_selector('#one').text
    dat2 = elt.find_elements_by_css_selector('#two')[1].text
    text = dat1 + dat2
except NoSuchElementException:
    text = elt.find_element_by_css_selector('#all').text
    item.set_description(text)

错误在这里:

NameError: name 'NoSuchElementException' is not defined

谷歌搜索/文档整理一无所获…让我感到奇怪的是,selenium可以引发异常但不能捕获它。


阅读 264

收藏
2020-06-26

共1个答案

一尘不染

您需要先导入异常

from selenium.common.exceptions import NoSuchElementException

然后你可以参考它

except NoSuchElementException:
    # handle the element not existing
2020-06-26