简体   繁体   English

如何使用 Selenium 和 Java 在自动化测试中单击按钮

[英]How to click a button in an automated test using Selenium and Java

I'm trying to automate a test using Selenium and I want to click a button using xpath.我正在尝试使用 Selenium 自动化测试,并且我想使用 xpath 单击按钮。 This is what I'm doing:这就是我正在做的事情:

WebElement LogInButton = driver.findElement(By.xpath("/login"));
LogInButton.click();

But I get an error that says:但我收到一条错误消息:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"/login"}

The only information I have about that button is this:我拥有的关于该按钮的唯一信息是:

<a href="/login">Login</a>

and the URL where it redirects to.以及它重定向到的 URL。 What am I doing wrong?我究竟做错了什么? What would be the correct way of referring to this button?引用此按钮的正确方法是什么? Any help please let me know.任何帮助请告诉我。 Thanks谢谢

To invoke click() on the element you can use either of the following Locator Strategies :要在元素上调用click() ,您可以使用以下任一Locator Strategies

  • Using linkText :使用链接文本

     driver.findElement(By.linkText("Login")).click();
  • Using cssSelector :使用cssSelector

     driver.findElement(By.cssSelector("a[href='/login']")).click();
  • Using xpath :使用xpath

     driver.findElement(By.xpath("//a[@href='/login' and text()='Login']")).click();

Best practices最佳实践

As you are invoking click() ideally you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies :当您理想地调用click()时,您需要为elementToBeClickable()诱导WebDriverWait并且您可以使用以下任一Locator Strategies

  • Using linkText :使用链接文本

     new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Login"))).click();
  • Using cssSelector :使用cssSelector

     new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href='/login']"))).click();
  • Using xpath :使用xpath

     new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/login' and text()='Login']"))).click();

Reference参考

You can find a couple of relevant discussions in:您可以在以下位置找到一些相关的讨论:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM