有时在页面上,我会寻找可能存在或不存在的元素。我想用 a 来尝试/捕捉这种情况,NoSuchElementException
当某些 HTML 元素不存在时,硒会抛出这种情况。原始异常:
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
谷歌搜索/文档一无所获……让我感到奇怪的是,硒可以抛出异常但无法捕捉到它。