Selenium期望条件 - 选择具有多个属性的元素

时间:2018-02-23 02:39:11

标签: python selenium

我尝试使用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中的错误还是我错误地使用它?

1 个答案:

答案 0 :(得分:0)

您需要处理以下几个事实:

  • 根据您共享的HTML, webelement 看起来不是可选,因此您无法选择你可以调用click(),这可以通过揭示确切的an-attribute属性来更清楚。

  • 您定义的WebDriverWait看起来很完美,但如果您尝试调用click()方法而不是expected_conditionspresence_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内。所以你需要先将{em> 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)