I'm pretty new to Selenium and automation. I'm trying to do automation for simple health declaration form page: https://forms.office.com/Pages/ResponsePage.aspx?id=bGOiBG0y_0iT-HCYdb06qZZ8CdlEQAhOkRllU1E9dVZUMVk1VTZFWThQV1FQUTFUV0FKNkNOVldMSi4u
To get to the textfield I used xpath:
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://forms.office.com/Pages/ResponsePage.aspx?id=bGOiBG0y_0iT-HCYdb06qZZ8CdlEQAhOkRllU1E9dVZUMVk1VTZFWThQV1FQUTFUV0FKNkNOVldMSi4u");
WebElement element = driver.findElement(By.xpath("//*[@id=\"form-container\"]/div/div/div[1]/div/div[1]/div[2]/div[2]/div[1]/div[2]/div[3]/div/div/div/input"));
element.click();
element.sendKeys("Testing");
Problem is sometime it doesn't find the element and the program crashes.
*** Element info: {Using=xpath, value=//*[@id="form-container"]/div/div/div[1]/div/div[1]/div[2]/div[2]/div[1]/div[2]/div[3]/div/div/div/input}
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:428)
at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
at automactionproj.MainActivity.hazaratBriyot(MainActivity.java:31)
at automactionproj.MainActivity.main(MainActivity.java:23)
Process finished with exit code 1
Any suggestions?
Using absolute xpath is not a good approach. I can't see the xpath matching in your application with the xpath string you have used in your code. Try using below relative xpath:
Even you can make xpath shorter and uniquely identifiable using unique attribute e.g.
//input[contains(@aria-labelledby,'question1-title')]
No need to perform click before enter text in textbox.