未找到元素时,Python Selenium崩溃

时间:2016-02-26 13:29:53

标签: python selenium selenium-webdriver

我正在使用Python Selenium从列表中打开一个URL并找到某个元素。像这样...

driver.get('http://www.example.com.com/')
inputElement = driver.find_element_by_id("my-field")

如果该元素存在,那么一切正常,但如果找不到该元素,则脚本崩溃并出现错误...

Unable to locate element:

这是正确的行为吗?有没有办法解决这个问题而不是崩溃?

3 个答案:

答案 0 :(得分:9)

这是正确的行为。

您可以捕获异常,就像任何异常一样:

from selenium.common.exceptions import NoSuchElementException
...
try:
    driver.get('http://www.example.com.com/')
    inputElement = driver.find_element_by_id("my-field")
except NoSuchElementException:
    print("couldn't find the element")

答案 1 :(得分:1)

是的,确实如此。来自文档:

  

...   使用此策略,第一个元素具有id属性值   将返回匹配的位置。如果没有元素匹配   id属性,将引发NoSuchElementException。

当然可以抓住异常(如另一个答案所述)。

你可以在这里找到文档: http://selenium-python.readthedocs.org/locating-elements.html#locating-by-id

答案 2 :(得分:1)

有时该元素不会一次出现,在这种情况下,我们需要使用显式等待。您只需检查元素是否存在,而不会崩溃。

browser = webdriver.Chrome()
wait = WebDriverWait(browser, 5)

def is_element_exist(text):
    try:
        wait.until(EC.presence_of_element_located((By.ID, text)))
    except TimeoutException:
        return False

没有try/ except的解决方案:

def is_element_exist(text):
    elements = wait.until(EC.presence_of_all_elements_located((By.ID, text)))
    return None if elements else False

显式等待如何工作,您可以阅读here

进口:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC