Đôi khi trên một trang, tôi sẽ tìm kiếm một phần tử có thể có hoặc không có ở đó. Tôi muốn thử/nắm bắt trường hợp này với một số NoSuchElementException
, mà selen đã được ném khi một số phần tử HTML không tồn tại. Ngoại lệ gốc:python selenium webscraping "NoSuchElementException" không được công nhận
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)
Trớ trêu thay, nó sẽ không để tôi bắt ngoại lệ này mà nó đã ném trước đó? Mã đây:
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)
Lỗi ở đây:
NameError: name 'NoSuchElementException' is not defined
Googling/tài liệu đã đưa ra không có gì ... và nó đập vào mắt tôi như lạ mà selen là tốt ném một ngoại lệ, nhưng không thể bắt nó.
không có trên tất cả các tài khoản. 'AttributeError: 'WebElement' đối tượng không có thuộc tính 'NoSuchElementException'',' AttributeError:' WebDriver 'đối tượng không có thuộc tính' NoSuchElementException'', 'ImportError: không thể nhập tên NoSuchElementException' – lollercoaster
Phiên bản đã chỉnh sửa (nhập) hoạt động! thx – lollercoaster
Cập nhật [2017]: từ selenium.common.exceptions nhập NoSuchElementException – Devin