检查元素是否存在 python selenium

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45695874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:13:22  来源:igfitidea点击:

Check if element exists python selenium

pythonseleniumselenium-webdriverwebdriverui-automation

提问by Nelly Kong

I'm trying to locate element by

我正在尝试通过以下方式定位元素

element=driver.find_element_by_partial_link_text("text")

in Python selenium and the element does not always exist. Is there a quick line to check if it exists and get NULL or FALSE in place of the error message when it doesn't exist?

在 Python selenium 中,元素并不总是存在。是否有快速行来检查它是否存在并在它不存在时获取 NULL 或 FALSE 来代替错误消息?

回答by Andersson

You can implement try/exceptblock as below to check whether element present or not:

您可以按如下方式实现try/except块来检查元素是否存在:

from selenium.common.exceptions import NoSuchElementException

try:
    element=driver.find_element_by_partial_link_text("text")
except NoSuchElementException:
    print("No element found")

or check the same with one of find_elements_...()methods. It should return you empty list or list of elements matched by passed selector, but no exception in case no elements found:

或使用其中一种find_elements_...()方法进行检查。它应该返回空列表或由传递的选择器匹配的元素列表,但在没有找到元素的情况下也不例外:

elements=driver.find_elements_by_partial_link_text("text")
if not elements:
    print("No element found")  
else:
    element = elements[0]  

回答by Alex Makarenko

Sometimes the element does not appear at once, for this case we need to use explicit wait:

有时元素不会立即出现,对于这种情况我们需要使用显式等待:

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

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

Solution without try/ except:

没有的解决方案try/ except

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

How explicit wait works you can read here.

您可以在此处阅读显式等待的工作原理。

Imports:

进口:

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