【问题标题】:Can't click on dropdown using xpath无法使用 xpath 点击下拉菜单
【发布时间】:2018-03-05 10:49:36
【问题描述】:

我尝试点击链接“Бренд”,但没有成功。我做错了什么?

driver.findElement(By.xpath("//div[@class='filter-title' and text()='Бренд']")).getText()  -works
driver.findElement(By.xpath("//div[@class='filter-title' and text()='Бренд']")).getText() - doesn't work. Why?

enter image description here

【问题讨论】:

  • 你有相同的代码行,怎么可能一个有效而另一个无效?
  • 能够单击一个元素,它应该是可见的,而不是被另一个元素“覆盖”。您可能需要在执行点击操作之前添加延迟,以确保元素完全可见

标签: selenium xpath selenium-webdriver


【解决方案1】:

WebElement.getText() 的行很有可能会起作用,但WebElement.click() 的行不会起作用,如下所示:

driver.findElement(By.xpath("//div[@class='filter-title' and text()='Бренд']")).getText() //works 
driver.findElement(By.xpath("//div[@class='filter-title' and text()='Бренд']")).click() //doesn't work. 

说明

这种行为的原因是 Client(即 Web 浏览器)将控件返回给 WebDriver 实例一次 'document.readyState' 等于 "complete" 实现了,很有可能预期的 WebElementpresent (元素存在,但不一定意味着该元素是可交互的) 和 visible(元素是可见的,并且高度和宽度都大于 0 )。所以你可以提取文本Бренд

但是 WebElementpresentvisible 但不保证 WebElement 也是 可点击,即可交互

在这里你可以找到关于'document.readyState' equal to "complete"的详细讨论

解决方案

要点击带有 Бренд 文本的 WebElement,您必须如下诱导 WebDriverWait

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='filter-title' and text()='Бренд']"))).click();

【讨论】:

    【解决方案2】:

    如果我能够从您的图像中正确提取信息,那么该类已经是一个唯一标识符。您可以使用driver.findElement(By.className("brand")).click();

    如果二级类“品牌”没有在其他任何地方使用,这应该可以工作。如果这不起作用,那么只需获取包含它的 div 的类:

    driver.findElement(By.className("initialDivClass")).findElement(By.className("brand")).click();
    

    【讨论】:

      猜你喜欢
      • 2016-09-01
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多