我正在尝试使用 Python 在 Selenium 中选择一个元素,如下所示:
<div class="class1 class2" an-attribute="attribute-value"></div>
并在预期条件下的等待中使用它,如下所示:
WebDriverWait(self.driver, timeout).until(
expected_conditions.presence_of_element_located(
(By.XPATH, '//div[@an-attribute="attribute-value"][@class="class1 class2"]')))
这种等待总是会导致 TimeoutException。
我还尝试了替代的 XPath 语法:
'//div[@an-attribute="attribute-value" and @class="class1 class2"]'
我可以在 find_element_by_xpath()
中使用相同的 XPath 值来获取此元素。
如果我暂停测试并检查浏览器 Web 控制台,我可以看到 div 确实具有此属性和类。对于 Firefox 和 Chromium 来说都是如此。
这是 Selenium 中的错误还是我使用不当?
最佳答案
您需要注意以下几个事实:
根据您共享的 HTML,webelement 看起来不可选择,因此您可能无法选择您可以调用
click()
,通过显示确切的an-attribute
属性,这会更加清晰。WebDriverWait您定义的看起来很完美,但如果继续尝试调用
click()
方法,则不要使用 expected_conditions您应该使用presence_of_element_ located
子句element_to_be_clickable
如下:WebDriverWait(driver, 20).until(expected_conditions.element_to_be_clickable((By.XPATH, "//div[@class='class1 class2' and @an-attribute='attribute-value']"))).click()
尽管
presence_of_element_ located
正在返回 TimeoutException,但在控制台中您能够找到它,这意味着该元素不在 Viewport 范围内。 。因此,您需要将 webelement 引入 Viewport 中首先如下:my_element = self.driver.find_element_by_xpath("//div[@class='class1 class2' and @an-attribute='attribute-value']") self.driver.execute_script("return arguments[0].scrollIntoView(true);", my_element)
关于python - Selenium预期条件-选择具有多个属性的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48940286/