【问题标题】:org.openqa.selenium.NoSuchElementException: Unable to locate element errororg.openqa.selenium.NoSuchElementException:无法定位元素错误
【发布时间】:2019-01-09 15:35:45
【问题描述】:

我在 JAVA 中使用 Selenium Web 驱动程序使用 Internet Explorer 和 Firefox 编写了以下代码。每次我遇到同样的错误。尝试使用“id”和“xpath”方法,但仍然失败。尝试添加一些延迟也,仍然不起作用。

我的 Firefox JAVA 代码:

package ieconnector;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;

public class FireFoxConnector {

public static void main(String[] args) {
    try{
    GetBrowserProperty gbp = new GetBrowserProperty();
    System.setProperty("webdriver.ie.driver",gbp.getIeConnection());
    System.setProperty("webdriver.gecko.driver","D:\\softwares\\Selenium\\geckodriver-v0.21.0-win64\\geckodriver.exe");
    WebDriver wb = new FirefoxDriver();
    Capabilities caps = ((RemoteWebDriver) wb).getCapabilities();
    System.out.println("Caps is "+caps);
    wb.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    //wb.navigate().to("https://somewebsite.com:22222/SSO/ui/SSOLogin.jsp");
    wb.get("https://somewebsite.com:22222/SSO/ui/SSOLogin.jsp");
    wb.manage().deleteAllCookies();
    wb.manage().window().maximize();
    //wb.findElement(By.id("usertxt")).sendKeys(("user").toUpperCase());
    //wb.findElement(By.className("passtxt")).sendKeys("password");
    //WebDriverWait wait = new WebDriverWait(wb,10);
    //WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("usertxt")));
    wb.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
    //wb.findElement(By.id("usertxt")).sendKeys("USER");
    wb.findElement(By.xpath("//*[@id='usertxt']")).sendKeys("USER");
    System.out.println("Testing is successful");
} catch (Exception e) {
    e.printStackTrace();
}

}

}

以下是我在IE/Firefox的开发者工具中的HTML代码截图。

【问题讨论】:

  • 在尝试执行 SendKeys 之前,您可以试试这个代码new WebDriverWait(Driver, TimeSpan.FromSeconds(30)).Until(ExpectedConditions.ElementToBeClickable(By.xpath("//*[@id='usertxt']")));
  • 你能分享错误/异常跟踪吗?

标签: java selenium selenium-webdriver xpath css-selectors


【解决方案1】:

根据您共享的 HTML 来定位 用户 ID 字段,您可以使用以下解决方案:

  • cssSelector:

    wb.findElement(By.cssSelector("input.txtbox#usertxt")).sendKeys("USER");
    
  • xpath:

    wb.findElement(By.xpath("//input[@class='txtbox' and @id='usertxt']")).sendKeys("USER");
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    相关资源
    最近更新 更多