26
有時在一個頁面上我會尋找一個可能或可能不存在的元素。我想用NoSuchElementException
來嘗試/捕捉這個案例,當某些HTML元素不存在時,硒正在拋出。原始異常:蟒蛇硒webscraping「NoSuchElementException」不承認
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)
具有諷刺意味的是,它不會讓我發現它之前拋出的異常嗎?代碼在這裏:
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
谷歌搜索/文件想出了什麼......它令我奇怪的是,硒是罰款拋出異常,但不能抓住它。
對所有帳戶都沒有。 'AttributeError:'WebElement'對象沒有屬性'NoSuchElementException','AttributeError:'WebDriver'對象沒有屬性'NoSuchElementException','ImportError:無法導入名稱NoSuchElementException' – lollercoaster
您的編輯版本(導入)的作品! thx – lollercoaster
Updated [2017]:from selenium.common.exceptions import NoSuchElementException – Devin