在python-selenium中,有两种查找元素的方法。
首先,您可以使用实际方法来查找元素,例如
element = find_element_by_xpath(myxpath)
其次,可以使用
WebDriverWait
来确保webdriver等待一段时间,直到找到处于给定状态的元素为止:element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, myxpath)))
对于后一种方法,您可以定义几个“预期条件”(请参见here):
element_located_to_be_selected, element_to_be_clickable, element_to_be_selected etc.
我的问题:仅使用第一种查找元素的方法,如何检查该元素处于哪个状态(以防万一我找到了该元素)。如何检查“可点击”或“可选”等?我可以使用
element
对象的属性来确定元素的状态吗? 最佳答案
不,没有直接方法可以通过Selenium检索WebElement的确切状态。
find_element_by_xpath(xpath)
find_element_by_xpath()只需使用xpath查找第一个匹配的WebElement。如果找不到匹配的元素,它将引发NoSuchElementException
但是Selenium提供了多种方法来验证WebElement的状态,如下所示:is_displayed()
:无论用户是否可见该元素,均返回一个布尔值(是/否)。is_enabled()
:返回一个布尔值(是/否),无论该元素是否启用。is_selected()
:无论是否选择元素,都返回一个布尔值(是/否)。
WebDriverWait()与Expected_conditions类结合使用
罐头expected_conditions通常可用于在元素达到确定状态时访问元素,如下所示:presence_of_element_located(locator)
提到:
class selenium.webdriver.support.expected_conditions.presence_of_element_located(locator)
An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible.
visibility_of_element_located(locator)
提到:class selenium.webdriver.support.expected_conditions.visibility_of_element_located(locator)
An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0.
element_to_be_clickable(locator)
提到:class selenium.webdriver.support.expected_conditions.element_to_be_clickable(locator)
An Expectation for checking an element is visible and enabled such that you can click it.
关于python - 如何获取python-selenium中元素的“状态”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52532460/