2013-10-05 25 views
26

時にはページ上で、私はそこにあるかもしれないかもしれない要素を探しています。私はこの事例をNoSuchElementExceptionでキャッチしようとしたかったのですが、特定のHTML要素が存在しないときにセレンが投げていました。元の例外:python serenium 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 

グーグル/ドキュメントが何を思い付いた...そしてそれはセレンが例外をスロー結構ですが、それをキャッチすることはできませんことを私はのように奇妙に当たります。

答えて

71

おそらくelt.NoSuchElementExceptionまたはdriver.NoSuchElementExceptionのいずれかを試してみてください。おそらくその1つの範囲で定義されています。代わりに、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

関連する問題