【问题标题】:How to find the element with the given xpath using Selenium and Java如何使用 Selenium 和 Java 查找具有给定 xpath 的元素
【发布时间】:2020-11-25 15:37:38
【问题描述】:
public void addCustInfo() throws InterruptedException
{   
    WebDriver driver;
    WebDriverManager.chromedriver().setup();
    driver = new ChromeDriver();
    driver.get("http://www.way2automation.com/angularjs-protractor/banking/#/manager");
    Thread.sleep(3000);
    driver.findElement(By.xpath("//button[@ng-click='addCust']")).click();
}

我尝试过使用相对和绝对 xpath,但它没有在脚本中识别。

【问题讨论】:

  • 请考虑勾选正确答案。

标签: java selenium xpath css-selectors nosuchelementexception


【解决方案1】:

其实@ng-click值包含函数调用"...()"

尝试添加

"//button[@ng-click='addCust()']"

【讨论】:

    【解决方案2】:

    ng-click 属性的值不是 addCust 而是addCust()

    所以对于元素上的click(),您可以使用以下任一Locator Strategies

    • cssSelector:

      driver.findElement(By.cssSelector("button[ng-click^='addCust']")).click();
      
    • xpath:

      driver.findElement(By.xpath("//button[starts-with(@ng-click, 'addCust')]")).click();
      

    但是,由于该元素是动态元素,因此要识别您需要为 elementToBeClickable() 诱导 WebDriverWait 的元素,您可以使用以下任一定位器策略

    • cssSelector:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[ng-click^='addCust']"))).click();
      
    • xpath:

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[starts-with(@ng-click, 'addCust')]"))).click();
      

    【讨论】:

      【解决方案3】:

      您也可以在定位器中使用 contains

      • 通过 XPATH

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(@ng-click, 'addCust')]"))).click();

      【讨论】:

      • 您提到了 contains,但在您的代码 sn-p 中,您使用了 starts-with 和另一个答案的副本。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 1970-01-01
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      相关资源
      最近更新 更多