2013-10-05 5 views
26

때때로 페이지에있을 수도 있고 없을 수도있는 요소를 찾고 있습니다. 나는 NoSuchElementException으로이 사건을 잡으려고했는데, 특정 HTML 요소가 존재하지 않았을 때 셀렌이 던져 넣었습니다. 원본 예외 :python 셀레늄 웹 스크랩 "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 

인터넷 검색/문서는 아무것도 와서 ... 그리고 셀레늄이 예외를 throw 괜찮지 만 그것을 잡을 수없는 나를 이상한 파업.

답변

71

아마도 elt.NoSuchElementException 또는 driver.NoSuchElementException 중 하나를 시도해보십시오. 아마도이 중 하나의 범위에서 정의 되었기 때문입니다. 또는 범위를 가져 오려면 from selenium import NoSuchElementException을 사용해야 할 수도 있습니다.

더 나은 아직 : from selenium.common.exceptions import NoSuchElementException

+1

모든 계정에. 'AttributeError : 'WebElement'객체에 'NoSuchElementException'속성이 없습니다., AttributeError : 'WebDriver'객체에 'NoSuchElementException'속성이 없습니다. 'ImportError : 이름을 가져올 수 없습니다. NoSuchElementException' – lollercoaster

+6

편집 한 버전 (가져 오기)이 작동합니다! thx – lollercoaster

+2

[2017] 업데이트 : selenium.common.exceptions에서 가져 오기 NoSuchElementException – Devin

관련 문제