[英]Check if element exists python selenium
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. 在Python selenium中,元素并不总是存在。 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?
是否存在快速行以检查它是否存在并在错误消息不存在时获取NULL或FALSE代替错误消息?
You can implement try
/ except
block 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. 或使用
find_elements_...()
方法之一检查相同内容。 It should return you empty list or list of elements matched by passed selector, but no exception in case no elements found: 它应该返回由传递的选择器匹配的空列表或元素列表,但是如果没有找到元素则没有异常:
elements=driver.find_elements_by_partial_link_text("text")
if not elements:
print("No element found")
else:
element = elements[0]
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.