Selenium WebDriver没有找到WebElements

时间:2017-08-03 20:03:27

标签: java css xpath selenium-webdriver

在我编写的脚本下面导航到所需的URL,但是没有输入用户名和密码的值。两个字段的Xpath和css都是正确的。有什么想法在这里出错吗?

org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class websiteClass {

    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://opensource.demo.orangehrmlive.com/");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        driver.findElement(By.xpath(".//*[@id='txtUsername']")).sendKeys("Admin");
        driver.findElement(By.xpath(".//*[@id='txtPassword']")).sendKeys("admin");      
        driver.findElement(By.xpath(".//*[@id='btnLogin']")).click();
    }

}

2 个答案:

答案 0 :(得分:1)

版本的geckodriver 0.18 driver.manage().window().maximize()抛出异常(实际上它是geckodriver bug)。

删除两行后:

   driver.manage().window().maximize();
   driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

代码适合我(程序使用geckodriver成功登录网站)。

还要确保设置webdriver系统属性(在WebDriver driver = new FirefoxDriver();之前)

System.setProperty("webdriver.gecko.driver", PATH_TO_GECKO_DRIVER);

我也尝试过您的代码而不对ChromeDriver进行任何更改,而且工作正常。

如果您仍有问题,请发布您的geckodriver版本和异常堆栈跟踪。

答案 1 :(得分:0)

it is working fine in the Firefox 43.0 and 2.51, I guess this is issue of Firefox browser. Either use gecko driver with selenium 3.3 jars or use Firefox 43.0 and 2.51 jars of selenium

use this for if you use chrome and update your chromedriver. For Firefox you need to change setproperty values only

System.setProperty("webdriver.chrome.driver", "E:\\software and tools\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
            driver.get("http://opensource.demo.orangehrmlive.com/");
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

            driver.findElement(By.xpath(".//*[@id='txtUsername']")).sendKeys("Admin");
            driver.findElement(By.xpath(".//*[@id='txtPassword']")).sendKeys("admin");      
            driver.findElement(By.xpath(".//*[@id='btnLogin']")).click();

            driver.close();