java - 在 Selenium Java 中查找元素的 Xpath

标签 java selenium xpath css-selectors webdriverwait

我试图用这个 XPATH 在 selenium 中找到一个元素。我在 Firefox 网络浏览器中得到了这个。

/html/body/div[5]/div[2]/div[9]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div[2]/div[1]/a
HTML代码
enter image description here
<a href="/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwiw7cbBv6LqAhVMAHIKHbbFCUYQFjAAegQIBxAB&amp;url=https%3A%2F%2Fwww.google.com%2Fgmail%2F&amp;usg=AOvVaw3mZ_qbD_gQyp_sqkjrwStn" onmousedown="return rwt(this,'','','','','AOvVaw3mZ_qbD_gQyp_sqkjrwStn','','2ahUKEwiw7cbBv6LqAhVMAHIKHbbFCUYQFjAAegQIBxAB','','',event)" data-ctbtn="2" data-cthref="/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwiw7cbBv6LqAhVMAHIKHbbFCUYQFjAAegQIBxAB&amp;url=https%3A%2F%2Fwww.google.com%2Fgmail%2F&amp;usg=AOvVaw3mZ_qbD_gQyp_sqkjrwStn"><br><h3 class="LC20lb DKV0Md">Gmail by Google</h3><div class="TbwUpd NJjxre"><cite class="iUh30 bc tjvcx">www.google.com<span class="eipWBe"> › gmail</span></cite></div></a>
我的 Selenium 代码
driver.findElement(By.xpath("/html/body/div[5]/div[2]/div[9]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div[2]/div[1]/a")).click();
driver.findElement(By.linkText("Sign in")).click();
但它不起作用。帮我。

最佳答案

由于元素是 Angular元素点击它,你需要使用WebDriverWaitelementToBeClickable()您可以使用以下任一 Locator Strategies :

  • cssSelector :
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[@href='https://www.google.com/gmail/'] h3"))).click();
    
  • xpath :
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//h3[text()='Gmail by Google']"))).click();
    
  • 关于java - 在 Selenium Java 中查找元素的 Xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62613168/

    相关文章:

    html - 文本的 XPath 不起作用

    java - 安卓Java : View cannot be applied to ()

    java - 在缓存中找不到元素 - 也许页面在查找后已更改

    javascript - Tomcat 7 Websocket 握手 : Unexpected response code: 404

    java - 使用 .getLocations 确定元素在两个浏览器中的移动

    python - Selenium webdriver 无法找到该元素。错误 - 消息 : element not visible

    xml - Powershell根据子节点值选择父xml节点并添加子元素

    php - Codeigniter 与 xpath 和重复 key 更新

    java - Bash检测bash中的彩色文本输出

    java - 如何在事务类上 Autowiring ?