Selenium:如何解决org.openqa.selenium.InvalidElementStateException:无效的元素状态 [英] Selenium : How to solve org.openqa.selenium.InvalidElementStateException: invalid element state

查看:3979
本文介绍了Selenium:如何解决org.openqa.selenium.InvalidElementStateException:无效的元素状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些在线文章,它们都指向了1个方向,即页面加载时找不到元素。在我的setData()中你可以看到我尝试过一些东西,比如使用wait,implicitwait和1st click然后发送用户名。然而,似乎没有任何工作。我还想过在pageProperties中使用wait但后来改变了主意,因为这可能是一个糟糕的设计。



错误:

 线程mainorg.openqa中的异常.selenium.InvalidElementStateException:无效元素状态

系统信息:Windows 10,ChromeDriver 2.37.544315,chrome = 65.0.3



代码

 公共课程巡演{

公共静态WebDriver驱动程序;

//浏览器URL信息
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);
返回司机;
}

//第一页的用户名和继续按钮属性
public void pageUserNameProperty(String un){
WebElement login = driver.findElement(By.xpath ( //输入[@ 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();

}
//来自第2页的密码和继续按钮属性
public void pagePassTourProperty(String psd){
WebElement password = driver.findElement(By.xpath( //输入[@ ID = '密码']));
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();

}

//从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();

}

}

错误:

 在端口2644上启动ChromeDriver 2.37.544315(730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7)
仅允许本地连接。
2018年4月18日上午07时09分26秒org.openqa.selenium.remote.ProtocolHandshake了createSession
产品介绍:检测到的话:在线程 主要 org.openqa.selenium OSS
例外。 InvalidElementStateException:无效的元素状态(会话信息:chrome = 65.0.3325.181)
(驱动程序信息:chromedriver = 2.37.544315(730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform = Windows NT 10.0.15063 x86_64)(警告:服务器未提供任何内容stacktrace information)命令持续时间或超时:0毫秒构建信息:版本:'3.11.0',修订版:'e59cfb3',时间:'2018-03-11T20:33:15.31Z'系统信息:主机:'XYZ', ip:'123',os.name:'Windows 10',os.arch:'amd64',os.version:'10 .0',java.version:'1.8.0_91'
驱动程序信息: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,rotate:false,setWindowRect:true,takesHeapSnapshot:true,takesScreenshot:true,unexpectedAlertBehaviour :, unhandledPromptBehavior :,,版本:65.0.3325.181,webStorageEnabled:true}
会话ID:3298d88e517d756790ab6792e45257f1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(原生方法)

感谢您的时间和建议。



实验:

 公共课游览{

public static WebDriver driver;

//浏览器URL信息
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);
返回司机;
}

//第一页的用户名和继续按钮属性
public void pageUserNameProperty(String un){
WebElement login = driver.findElement(By.xpath ( //输入[@ ID = 'usernameOrEmail']));
WebElement cont_btn = driver.findElement(By.xpath(// button [contains(@ type,'submit')]));

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

}
//来自第2页的密码和继续按钮属性
public void pagePasswordProperty(String psd){
WebElement password = driver.findElement(By.xpath( //输入[@ ID = '密码']));
WebElement lgn_btn = driver.findElement(By.xpath(// button [contains(@ type,'submit')]));

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

//方法 - isElementExists检查该元素是否存在
public boolean isElementExists(By xpath){
return driver.findElements(By。 xpath(// input [@ id ='usernameOrEmail']))。size()> 0;
}

/ *创建一个方法waitForElement并以秒为单位传递等待时间,它不是硬代码等待,因为
*会不断检查该元素是否存在或不然后它将在
*上等待1秒for for循环的每次迭代
* /
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();
}
返回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();
}

}


解决方案

错误说明了一切:

 线程main中的异常org.openqa.selenium.InvalidElementStateException:无效的元素状态

错误清楚地表明您尝试与之交互的元素处于行动期间无法执行。



InvalidElementStateException








更新



根据你的评论中的反问题, WebDriverWait 民意调查 HTML DOM 在特定时间间隔(默认为500毫秒),直到配置的时间(在您的情况下为30秒)。一旦 ExpectedConditions 。例如,如果在1秒内找到所需元素,则返回该元素并执行下一行代码。没有延误。根据 WebDriverWait 构造函数你总是可以配置 timeOutInSeconds sleepInMillis 即轮询间隔。



在这里你可以找到详细的讨论用显式等待替换隐式等待(硒) webdriver& java)


I have read a few online articles and they all point to 1 direction and that is when the page is loading the element is not found. In my setData() you can see I have tried a few things such as use of wait, implicitwait and 1st click and then send the username. However nothing seems to be working. I also thought of using "wait" inside pageProperties but later changed my mind because that would probably be a bad design.

Error :

Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state

System information: Windows 10, ChromeDriver 2.37.544315, chrome=65.0.3

Code:

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();

    }

}

Error:

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)    

Thank You for your time and suggestion.

Experiment:

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();
    }

}

解决方案

The error says it all :

Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state

The error clearly says that the element with which you are trying to interact is in a state during which actions cannot be performed.

InvalidElementStateException

InvalidElementStateException is a type of WebDriverException which indicates that a WebElement with whom you are trying to interact is in a state in which actions cannot be performed with it. Such instances may arise when an element is being obscured by another element while clicking or the desired element perhaps is not being visible on the HTML DOM.

Solution

You have to consider a few facts as follows :

  • Never mixup implicitlyWait() and WebDriverWait() as the documentation clearly mentions the following :

Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example setting an implicit wait of 10 seconds and an explicit wait of 15 seconds, could cause a timeout to occur after 20 seconds.

So you need to remove all the instances of implicitlyWait().

  • As you need to send characters to the Email Address or Username field so instead of ExpectedConditions method visibilityOfElementLocated() you need to use elementToBeClickable() method.
  • A simple script to access the url https://wordpress.com/log-in and send characters to the Email Address or Username field is as follows :

    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");
    

  • Snapshot of the WebClient :


Update

As per your counter question within your comments the WebDriverWait polls the HTML DOM at certain intervals (default 500 ms) till the configured amount of time (30 seconds in your case). The element/s is/are returned back as soon as the ExpectedConditions is met. For example, if the desired element is found within 1 second, it is returned and your next line of code executes. There is no delay involved. As per the WebDriverWait constructor you can always configure the timeOutInSeconds and sleepInMillis i.e. polling interval.

Here you can find a detailed discussion on Replace implicit wait with explicit wait (selenium webdriver & java)

这篇关于Selenium:如何解决org.openqa.selenium.InvalidElementStateException:无效的元素状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆