webscraping python selen „NoSuchElementException” nie został rozpoznany
Czasami na stronie szukam elementu, który może, ale nie musi tam być. Chciałem spróbować / złapać tę sprawę za pomocąNoSuchElementException
, który selen rzucał, gdy pewne elementy HTML nie istniały. Oryginalny wyjątek:
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)
Jak na ironię, nie pozwoli mi złapać tego wyjątku, który wcześniej rzucał? Kod tutaj:
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)
Błąd tutaj:
NameError: name 'NoSuchElementException' is not defined
Googling / dokumentacja nic nie wymyśliła ... i wydaje mi się dziwne, że selen jest w porządku, rzucając wyjątek, ale nie może go złapać.