有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java组织。openqa。硒。NoTouchElementException:无法定位元素错误

我已经用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代码的截图

HTML


共 (1) 个答案

  1. # 1 楼答案

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

    • cssSelector

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

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