Java Selenium:如何解决org.openqa.Selenium.InvalidelementState异常:元素状态无效

Java Selenium:如何解决org.openqa.Selenium.InvalidelementState异常:元素状态无效,java,selenium,selenium-webdriver,webdriver,Java,Selenium,Selenium Webdriver,Webdriver,我读过一些在线文章,它们都指向一个方向,即当页面加载元素时,找不到元素。在my setData()中,您可以看到我尝试了一些方法,例如使用wait、implicitwait和第一次单击然后发送用户名。然而,一切似乎都不起作用。我还想过在pageProperties中使用“wait”,但后来改变了主意,因为这可能是一个糟糕的设计 错误: Exception in thread "main" org.openqa.selenium.InvalidElementStateException: inva

我读过一些在线文章,它们都指向一个方向,即当页面加载元素时,找不到元素。在my setData()中,您可以看到我尝试了一些方法,例如使用wait、implicitwait和第一次单击然后发送用户名。然而,一切似乎都不起作用。我还想过在pageProperties中使用“wait”,但后来改变了主意,因为这可能是一个糟糕的设计

错误:

Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state
系统信息:Windows 10,ChromeDriver 2.37.544315,chrome=65.0.3

代码

public class Tour {

    public static WebDriver driver;

    //browser URL information
    public WebDriver getBrowser(String browser, String url){
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Downloads\\chromedriver.exe");

        if(browser.equals("cc")){
            driver= new ChromeDriver();
        }
        driver.get(url);
        return driver;
    }

    // User name and continue button property from 1st page
    public void pageUserNameProperty(String un){
        WebElement login=driver.findElement(By.xpath("//input[@id='usernameOrEmail']"));
        WebElement cont_btn=driver.findElement(By.xpath("//button[contains(@type,'submit')]"));

        //WebDriverWait wait = new WebDriverWait(driver,30);
        //wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='usernameOrEmail']")));
        login.sendKeys(un);
        cont_btn.click();

    }
    // Password and continue button property from 2nd page
    public void pagePassTourProperty(String psd){
        WebElement password=driver.findElement(By.xpath("//input[@id='password']"));
        WebElement lgn_btn=driver.findElement(By.xpath("//button[contains(@type,'submit')]"));

        //WebDriverWait wait = new WebDriverWait(driver,30);
        //wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='usernameOrEmail']")));
        password.sendKeys(psd);
        lgn_btn.click();

    }

    // Supply Data for test from excel
    public void setData(){
        Tour tour= new Tour();
        tour.getBrowser("cc", "https://wordpress.com/log-in");
        WebDriverWait wait = new WebDriverWait(driver,30);
        WebElement login_field=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='usernameOrEmail']")));
        login_field.click();
        //driver.manage().timeouts().implicitlyWait(18, TimeUnit.SECONDS);
        tour.pageUserNameProperty("JoeThomas");
        //wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='passTour']")));
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        tour.pagePassTourProperty("psd231");
    }

    public static void main(String[] args) {
        Tour tour= new Tour();
        tour.setData();

    }

}
错误:

Starting ChromeDriver 2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7) on port 2644 
Only local connections are allowed. 
Apr 18, 2018 7:09:26 AM org.openqa.selenium.remote.ProtocolHandshake createSession 
INFO: Detected dialect: OSS 
Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state   (Session info: chrome=65.0.3325.181)   
(Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Windows NT 10.0.15063 x86_64) (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 0 milliseconds Build info: version: '3.11.0', revision: 'e59cfb3', time: '2018-03-11T20:33:15.31Z' System info: host: 'XYZ', ip: '123', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_91' 
Driver info: org.openqa.selenium.chrome.ChromeDriver Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.37.544315 (730aa6a5fdba15..., userDataDir: C:\Users\CHQ-SH~1\AppData\L...}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 65.0.3325.181, webStorageEnabled: true} 
Session ID: 3298d88e517d756790ab6792e45257f1    
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)    
谢谢你的时间和建议

实验:

public class Tour {

    public static WebDriver driver;

    //browser URL information
    public WebDriver getBrowser(String browser, String url){
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\chq-sheikhr\\Downloads\\chromedriver.exe");

        if(browser.equals("cc")){
            driver= new ChromeDriver();
        }
        driver.get(url);
        return driver;
    }

    // User name and continue button property from 1st page
    public void pageUserNameProperty(String un){
        WebElement login=driver.findElement(By.xpath("//input[@id='usernameOrEmail']"));
        WebElement cont_btn=driver.findElement(By.xpath("//button[contains(@type,'submit')]"));

        login.sendKeys(un);
        cont_btn.click();

    }
    // Password and continue button property from 2nd page
    public void pagePasswordProperty(String psd){
        WebElement password=driver.findElement(By.xpath("//input[@id='password']"));
        WebElement lgn_btn=driver.findElement(By.xpath("//button[contains(@type,'submit')]"));

        password.sendKeys(psd);
        lgn_btn.click();
    }

    // A method - isElementExists to check whether that element exists or not
    public boolean isElementExists(By xpath){
        return driver.findElements(By.xpath("//input[@id='usernameOrEmail']")).size() > 0;
    }

    /*create a method waitForElement and pass wait time in seconds to it, it is not a hard code wait as it
     *  will continuously check whether that element is exist or not and then it will wait for 1 seconds on 
     *  every iteration of for loop
     */
    public boolean waitForElement(int timeInSeconds, By xpath){
        try{
            for(int i=0;i<timeInSeconds;i++){
                if(isElementExists(xpath))
                    return true;
                Thread.sleep(1000);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return false;
    }

    public void setData(){
        Tour tour= new Tour();
        tour.getBrowser("cc", "https://wordpress.com/log-in");
        tour.waitForElement(10, By.xpath("//input[@id='usernameOrEmail']"));
        tour.pageUserNameProperty("JoeThoman");
        tour.pagePasswordProperty("pasd123");


    }

    public static void main(String[] args) {
        Tour tour= new Tour();
        tour.setData();
    }

}
公共课旅游{
公共静态WebDriver;
//浏览器URL信息
公共WebDriver getBrowser(字符串浏览器、字符串url){
System.setProperty(“webdriver.chrome.driver”,“C:\\Users\\chq sheikhr\\Downloads\\chromedriver.exe”);
if(browser.equals(“cc”)){
驱动程序=新的ChromeDriver();
}
获取(url);
返回驱动器;
}
//第1页的用户名和“继续”按钮属性
公共无效PageUserName属性(字符串un){
WebElement login=driver.findElement(By.xpath(//input[@id='usernameOrEmail']);
WebElement cont_btn=driver.findElement(By.xpath(//button[contains(@type,'submit')]);
登录。发送密钥(un);
继续点击();
}
//第2页的密码和继续按钮属性
公共无效pagePasswordProperty(字符串psd){
WebElement password=driver.findElement(By.xpath(//input[@id='password']);
WebElement lgn_btn=driver.findElement(By.xpath(//button[contains(@type,'submit')]);
密码。发送键(psd);
lgn_btn.单击();
}
//方法-isElementExists检查该元素是否存在
公共布尔isElementExists(通过xpath){
返回driver.findElements(By.xpath(//input[@id='usernameOrEmail']).size()>0;
}
/*创建一个waitForElement方法并将等待时间(以秒为单位)传递给它,因为它不是硬代码等待
*将持续检查该元素是否存在,然后在上等待1秒
*for循环的每次迭代
*/
公共布尔waitForElement(int-timeInSeconds,通过xpath){
试一试{

对于(int i=0;i要使其一致,请遵循以下步骤:

A)创建一个方法-isElementExists来检查元素是否存在,如下所示:

public boolean isElementExists(String xpathOfElement){
    return driver.findElements(By.xpath(xpathOfElement)).size() > 0;
}
public boolean waitForElement(int timeInSeconds, String xpathOfElement){
    try{
        for(int i=0;i<timeInSeconds;i++){
            if(isElementExists(xpathOfElement))
                return true;
            Thread.sleep(1000);
        }
    }catch(Exception ex){
        ex.printStackTrace();
    }
    return false;
}
B)现在创建一个方法waitForElement并将等待时间以秒为单位传递给它,这不是一个硬代码等待,因为它将持续检查元素是否存在,然后在for循环的每次迭代中等待1秒,如下所示低点:

public boolean isElementExists(String xpathOfElement){
    return driver.findElements(By.xpath(xpathOfElement)).size() > 0;
}
public boolean waitForElement(int timeInSeconds, String xpathOfElement){
    try{
        for(int i=0;i<timeInSeconds;i++){
            if(isElementExists(xpathOfElement))
                return true;
            Thread.sleep(1000);
        }
    }catch(Exception ex){
        ex.printStackTrace();
    }
    return false;
}
public boolean waitForElement(int-timeinsectonds,String-xpathofeelement){
试一试{

对于(int i=0;i要使其一致,请遵循以下步骤:

A)创建一个方法-isElementExists来检查元素是否存在,如下所示:

public boolean isElementExists(String xpathOfElement){
    return driver.findElements(By.xpath(xpathOfElement)).size() > 0;
}
public boolean waitForElement(int timeInSeconds, String xpathOfElement){
    try{
        for(int i=0;i<timeInSeconds;i++){
            if(isElementExists(xpathOfElement))
                return true;
            Thread.sleep(1000);
        }
    }catch(Exception ex){
        ex.printStackTrace();
    }
    return false;
}
B)现在创建一个方法waitForElement并将等待时间以秒为单位传递给它,这不是一个硬代码等待,因为它将持续检查元素是否存在,然后在for循环的每次迭代中等待1秒,如下所示低点:

public boolean isElementExists(String xpathOfElement){
    return driver.findElements(By.xpath(xpathOfElement)).size() > 0;
}
public boolean waitForElement(int timeInSeconds, String xpathOfElement){
    try{
        for(int i=0;i<timeInSeconds;i++){
            if(isElementExists(xpathOfElement))
                return true;
            Thread.sleep(1000);
        }
    }catch(Exception ex){
        ex.printStackTrace();
    }
    return false;
}
public boolean waitForElement(int-timeinsectonds,String-xpathofeelement){
试一试{
对于(int i=0;i此错误消息

Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state
…表示您尝试与之交互的元素处于无法执行操作的状态


InvalidElementStateException 是一种类型,表示您尝试与之交互的WebElement处于无法对其执行操作的状态。当单击时某个元素被另一个元素遮挡,或者所需的元素可能在屏幕上不可见时,可能会出现这种情况


解决方案 你必须考虑以下几个事实:

System.setProperty("webdriver.gecko.driver", "C:/path/to/geckodriver.exe");
WebDriver driver =  new FirefoxDriver();
driver.get("https://wordpress.com/log-in");
new WebDriverWait(driver,30).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='usernameOrEmail']"))).sendKeys("JoeThomas");
  • 切勿隐式混淆wait()和WebDriverWait(),因为清楚地提到了以下内容:
不要混合使用隐式和显式等待。这样做可能会导致不可预测的等待时间。例如,将隐式等待设置为10秒,显式等待设置为15秒,可能会导致20秒后出现超时

因此,您需要删除隐式wait()的所有实例

  • 由于您需要将字符发送到电子邮件地址或用户名字段,因此需要使用方法来代替ExpectedConditions方法
    visibilityOfElementLocated()
  • 访问url的简单脚本
    https://wordpress.com/log-in
    并将字符发送到电子邮件地址或用户名字段,如下所示:

    System.setProperty("webdriver.gecko.driver", "C:/path/to/geckodriver.exe");
    WebDriver driver =  new FirefoxDriver();
    driver.get("https://wordpress.com/log-in");
    new WebDriverWait(driver,30).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='usernameOrEmail']"))).sendKeys("JoeThomas");
    
  • WebClient的快照:


使现代化 根据您评论中的反问题,WebDriverWait会以特定的间隔(默认为500毫秒)轮询,直到配置的时间量(您的情况下为30秒)。元素将在满足后立即返回。例如,如果在1秒内找到所需元素,则返回该元素并执行下一行代码。不涉及延迟。根据构造函数,您始终可以配置timeOutInSecondssleepInMillis,即轮询间隔


参考 有关详细讨论,请参见:

此错误消息

Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state
…表示您使用的元素