[英]How to use 'expected conditions' to check for an element in python-selenium?
我无法理解如何使用“预期条件”来检查元素是否存在。 鉴于此文档,根本不清楚如何使用它。 我试过下面的代码
def _kernel_is_idle(self):
return EC.visibility_of_element_located((By.XPATH, '//*[@id="kernel_indicator_icon" and @title="Kernel Idle"]'))
以检查元素(可作为类中的方法调用)的想法。 有两件事没有任何意义:
根据文档(我必须查找源代码!),此方法应返回True
或False
。 但是,它返回以下内容:
<selenium.webdriver.support.expected_conditions.visibility_of_element_located object at 0x110321b90>
怎么能没有此功能工作webdriver
? 通常你总是有这样的电话
driver.do_something()
但是对于“预期条件”,webdriver 的参考在哪里?
以更有条理的方式总结:
__call__()
魔术方法的函数或类) 预期条件应该在WebDriverWait()
实例的until()
方法中使用:
wait = WebDriverWait(driver, 10) wait.until(<Expected_condition_here>)
预期条件的结果不一定只是True
/ False
。 结果将由WebDriverWait
进行真实性测试。 注意: WebElement
实例是“真实的”。 在此处阅读有关 Python 真实性的更多信息
当预期条件返回WebElement
实例时,这非常方便。 它允许立即链接到一个元素,而无需再次找到它:
button = wait.until(EC.element_to_be_clickable((By.ID, "my_id"))) button.click()
看来你快到了。
Documentation
清楚地说明了以下内容:
class selenium.webdriver.support.expected_conditions.visibility_of_element_located(locator)
其定义为:
检查元素是否存在于页面的 DOM 上并且可见的期望。 可见性意味着元素不仅被显示,而且具有大于 0 的高度和宽度。 locator - 用于查找元素
returns the WebElement once it is located and visible
因此,当您提到:
return EC.visibility_of_element_located((By.XPATH, '//*[@id="kernel_indicator_icon" and @title="Kernel Idle"]'))
发现的WebElement
返回如下:
<selenium.webdriver.support.expected_conditions.visibility_of_element_located object at 0x110321b90>
甚至Source Code
说相同:
try:
return _element_if_visible(_find_element(driver, self.locator))
当搜索不成功时:
except StaleElementReferenceException:
return False
expected conditions
工作方式是定义WebDriverWait
。 您可以使用WebDriver
的实例和超时来创建它。 WebDriverWait
有一个until()
方法,该方法将采用expected condition
并等待它被满足或直到超时过去。 因此,而不是只是EC.visibility_of_element_located((By.XPATH, '//*[@id="kernel_indicator_icon" and @title="Kernel Idle"]'))
你应该使用:
WebDriverWait(yourdriver, timeout).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="kernel_indicator_icon" and @title="Kernel Idle"]')))
编辑我应该注意,这不会返回True
或False
。 如果已找到并且可见,这将返回WebElement
。 否则它将引发TimeOutException
。 来源
你快成功了! 你想要的可能是:
def _kernel_is_idle(self):
return EC.visibility_of_element_located(
(By.XPATH, '//*[@id="kernel_indicator_icon" and @title="Kernel Idle"]')
)(driver)
在这里,您应该将 webdriver 对象作为参数传递。
首先,您需要从 selenium.webdriver.support 导入 expected_conditions 模块。 使用此模块,您还可以检查元素的多个条件并给出预期时间
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("http://domain/element")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "idxxx"))
)
finally:
driver.quit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.