2013-10-05 19 views
26

Bazen bir sayfada olabilecek veya bulunmayan bir öğe arayacağım. Bu örneği, belirli HTML öğeleri olmadığında selenyumun attığı NoSuchElementException ile denemek/yakalamak istedim. Orijinal istisna: İronikpython selenium webscraping "NoSuchElementException" tanınmadı

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) 

, benim daha önce atma bu durum yakalamak izin vermiyor? Burada Kodu: Burada

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) 

Hata:

NameError: name 'NoSuchElementException' is not defined 

Googling/dokümantasyon hiçbir şey ile geldi ... ve selenyum istisna atma iyi ama bunu yakalamak olamayacağını bana garip vurur.

cevap

71

elt.NoSuchElementException veya driver.NoSuchElementException'dan birini deneyin, çünkü bunlardan biri kapsamında tanımlanmıştır. Alternatif olarak, kapsam içine getirmek için from selenium import NoSuchElementException kullanmanız gerekebilir.

Daha iyi: from selenium.common.exceptions import NoSuchElementException

+1

tüm hesaplarda yok. AttributeError: 'WebElement' nesnesinin 'NoSuchElementException' özelliği yok, 'AttributeError:' WebDriver 'nesnesinin' NoSuchElementException 'özelliği yok, ImportError: NoSuchElementException adını alamıyor. – lollercoaster

+6

Düzenlediğiniz sürümünüz (import) çalışıyor! thx – lollercoaster

+2

Güncelleme [2017]: from selenium.common.exceptions ithalat NoSuchElementException – Devin