本文介绍了python硒网络抓取“ NoSuchElementException”未能识别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有时我会在页面上寻找可能存在或可能不存在的元素。我想用 NoSuchElementException
尝试/捕获这种情况,当某些HTML元素不存在时,硒会抛出该异常。原始异常:
Sometimes on a page I'll be looking for an element which may or may not be there. I wanted to try/catch this case with a NoSuchElementException
, which selenium was throwing when certain HTML elements didn't exist. Original exception:
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/[email protected]/components/driver_component.js:8899)
at FirefoxDriver.prototype.findChildElement (file:///var/folders/6q/7xcjtgyj32nfc2yp_y5tr9pm0000gn/T/tmp63Mz2a/extensions/[email protected]/components/driver_component.js:8911)
at DelayedCommand.prototype.executeInternal_/h (file:///var/folders/6q/7xcjtgyj32nfc2yp_y5tr9pm0000gn/T/tmp63Mz2a/extensions/[email protected]/components/command_processor.js:10840)
at DelayedCommand.prototype.executeInternal_ (file:///var/folders/6q/7xcjtgyj32nfc2yp_y5tr9pm0000gn/T/tmp63Mz2a/extensions/[email protected]/components/command_processor.js:10845)
at DelayedCommand.prototype.execute/< (file:///var/folders/6q/7xcjtgyj32nfc2yp_y5tr9pm0000gn/T/tmp63Mz2a/extensions/[email protected]/components/command_processor.js:10787)
具有讽刺意味的是,它不会让我捕捉到它之前抛出的异常吗?代码在这里:
Ironically, it won't let me catch this exception which it was throwing before? Code here:
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
Google搜索/文档没有任何内容...而让我感到惊讶的是,硒可以抛出异常但不能捕获它。
Googling/documentation came up with nothing...and it strikes me as strange that selenium is fine throwing an exception but can't catch it.
推荐答案
您需要先导入异常
from selenium.common.exceptions import NoSuchElementException
然后您可以引用
except NoSuchElementException:
# handle the element not existing
这篇关于python硒网络抓取“ NoSuchElementException”未能识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!