stale element reference: while trying to access a drop down button - java

Have been trying to access the drop down button element using selenium, the page asks for a pincode on opening and after entering it and clicking ok it refreshes and then when i try to find the element by id or class name or css selector it throws an exception stating " stale element reference: element is not attached to the page document ", It will be helpful to know where im going wrong with the following code, Thanx in advance !
here is my code :
package introduction;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Locators {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "D:/Temp/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
driver.get("https://v5.fipola.in/");
driver.findElement(By.id("DelLocation")).sendKeys("600020");
driver.findElement(By.className("top_pincode_select")).click();
driver.findElement(By.className("customer-name")).click(); //error on this line
}
}
image with the dom
I solved it by introducing thread.sleep(3000) line with interrupted exception on void main, but my question is why does the
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5)); did not work ? does that suppose to make the webdriver wait for 5 seconds until the page gets reloaded after entering the pincode and click ok ?

Related

org.openqa.selenium.NoAlertPresentException: No modal dialog is currently open

I'm writing a small piece of code to automate a daily task. As part of this task I login into our internal website and click on a specific tab which prompts a dialog box where i need to click on yes or no to disable. I used an alert statement but it still throws the below error. Also I'm doing this for the first time in my career. Never done this before. Can anyone please help me with this ?
Exception in thread "main" org.openqa.selenium.NoAlertPresentException: No modal dialog is currently open
My code:
package test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class automate {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver","C:\\Users\\405325\\eclipse-workspace\\Monitoring\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("https://www.mywebsite.com");
driver.findElement(By.name("userName")).sendKeys("myusername");
driver.findElement(By.name("passWord")).sendKeys("mypassword");
driver.findElement(By.name("loginForm")).click();
driver.findElement(By.xpath("//*[#id=\"tabIndent\"]/div/table/tbody/tr[7]/td[2]/a/font")).click();
Alert alert = driver.switchTo().alert();
driver.findElement(By.xpath("//*[#id=\"dialog20HideableContent\"]/table/tbody/tr[1]/td/form/div/table/tbody/tr/td[2]/div/table[1]/tbody/tr/td")).click();
}
}
As per you question, your code trials and error you are seeing it appears that the dialog box is a Modal Dialog Box and to invoke click() on it you have to induce WebDriverWait as follows :
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"dialog20HideableContent\"]/table/tbody/tr[1]/td/form/div/table/tbody/tr/td[2]/div/table[1]/tbody/tr/td"))).click();

Unable to locate element radio botton in Selenium webdriver

I am a newbie trying to learn automation using the tool Selenium. I am trying to automate this website -
http://newtours.demoaut.com/
where I login and try to access this radio button (one way, round way )for flight finder.
But i am getting the error Unable to locate the element.
Tried the following.
Tried to locate the element using Xpath obtained from firebug.
Used the following Xpath composed from the html code to locate the radio button
//*[#type='radio']//*[#value='oneway']
//*[contains(#type,'radio')]
//*[contains(text(),'oneway']
//input[#type='radio' AND #value='oneway']
Also tried CSS selector to locate the element.
driver.findElement(By.cssSelector("input[type=radio][value=oneway]"))
Tried adding wait times using implicit wait and thread.sleep
The HTML script for the radio button as obtained from firebug is -
input type="radio" checked="" value="roundtrip" name="tripType"
Round Trip
input type="radio" value="oneway" name="tripType"
One Way
Given below is my code -
package gurutrial2;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class gurutrial2
{
public static WebDriver driver;
#BeforeTest
public final void preTest() {
System.setProperty("webdriver.firefox.marionette", "C:/Users/serajendran/Downloads/geckodriver-0.10.0 (1)");
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);
driver.get("http://newtours.demoaut.com/");
driver.manage().window().maximize();
System.out.println(driver.getTitle());
Assert.assertEquals("Welcome: Mercury Tours", driver.getTitle());
}
#Test
public final void login() {
driver.findElement(By.name("userName")).sendKeys("invalidUN");
driver.findElement(By.name("password")).sendKeys("invalidPW");
driver.findElement(By.name("login")).click();
System.out.println("login in progress");
}
#Test
public final void flightFinder() {
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement oneWayRadioButton = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("oneway")));
oneWayRadioButton.click();
System.out.println("Clicked One Way");
}
}
Any help would be deeply appreciated.
//*[#type='radio']//*[#value='oneway'] - you're looking for an element of type radio and value oneway.. this xpath look for an element of type radio that has a child element with value oneway.
//*[contains(#type,'radio')] - you'll get multiple results for this
//*[contains(text(),'oneway'] - the text is not oneway, only the value attribute is oneway, the text contains 'One Way'
//input[#type='radio' AND #value='oneway'] - this should work if you change 'AND' to 'and'
Following solution worked for me on the newtour site -
driver.findElement(By.cssSelector("input[value='oneway']")).click();
Actually the problem is in your test Methods
In TestNG the execution of #Test methods is in alphabetic order by default. So in your code flightFinder() method executing before login() So even you are using right locator to click on radio button, It will show the exception.
Solution:
Maintains your method name in alphabetic order
Use priority under #Test annotation for the methods e.g. - #Test(priority = 1)
Create dependency test e.g. -
#Test()
public final void login()
{
//code
}
#Test(dependsOnMethods={"login"})
public final void flightFinder()
{
//code
}
Update your code as below and try -
#Test
public final void doLogin() {
driver.findElement(By.name("userName")).sendKeys("invalidUN");
driver.findElement(By.name("password")).sendKeys("invalidPW");
driver.findElement(By.name("login")).click();
System.out.println("login in progress");
}
#Test()
public final void flightFinder() {
driver.findElement(By.xpath("//input[#type='radio' and #value='oneway']")).click();
System.out.println("Clicked One Way");
}

Occasional link's handling

Main page contains more than 300 links, clicking on each link on main page opens new window (of course) with table. I always need table value from the same position, yet... sometimes (but only sometimes) that (needed) table value is actally also a link which opens new window after clicking on it.
If clicking on that table value opens new window (with new table) I need specific table value from that new window, if not (if original table value is not a link) I need only original table value.
I tried with the code below but error occured...
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[#id='aodds-info']/div[2]/table/tbody/tr[3]/td[2]"}
Command duration or timeout: 33 milliseconds
package newpackage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class newdist {
public static void main(String[] args) throws IOException, InterruptedException {
// Open main page
WebDriver driver = new FirefoxDriver();
driver.get("Main page link");
Thread.sleep(5000);
// Maximize main page window
driver.manage().window().maximize();
Thread.sleep(1000);
// List off all links on Main page
List<WebElement> lista1 = driver.findElements(By.cssSelector(".first-cell.tl>a"));
// loop trough all links on Main page
for(int j=0;j<lista1.size();j++){
WebElement link = lista1.get(j);
List<WebElement> links = driver.findElements(By.cssSelector(".first-cell.tl>a"));
String homePage = driver.getWindowHandle();
link.click();
Thread.sleep(3000);
// Window handles block
Set<String>windows=driver.getWindowHandles();
Iterator iterator = windows.iterator();
String currentWindowId;
while (iterator.hasNext()){
currentWindowId = iterator.next().toString();
if(! currentWindowId.equals(homePage)){
driver.switchTo().window(currentWindowId);
Thread.sleep(3000);
// "clicking" on specific table value (clicking maybe opens new window)
driver.findElement(By.xpath(".//*[#id='sortable-1']/tbody/tr[6]/td[1]/span")).click();
Thread.sleep(3000);
// if clicking opens new window print specific value from table in that new window
try {
String s0 = driver.findElement(By.xpath(".//*[#id='aodds-info']/div[2]/table/tbody/tr[3]/td[2]")).getText();
System.out.println(s0);
}
// if clicking doesn't open new window print current table value from current window
catch (NoSuchElementException e){
String s0 = driver.findElement(By.xpath(".//*[#id='sortable-1']/tbody/tr[6]/td[1]/span")).getText();
System.out.println(s0);
}
// return to Main page
finally{
driver.close();
driver.switchTo().window(homePage);
Thread.sleep(2000);
}
}
}
}
}
}
The NoSuchElementException is imported from java.util. To catch web elements exception you need to import from org.openqa.selenium.
As a side note, using explicit and implicit wait is much better practice then using Thread.sleep.

How to remove an element attribute with JavascriptExecutor and Selenium WD?

I have the below code to set up an auto bid on an auction site.
I have gotten stuck as the confirm button is disabled until the user types keypresses into the text field.
I can populate the field using selenium.type however this does not remove the disabled attribute from the button.
I was hoping there might be a way of removing the attribute once the .type command has finished.
I have searched many pages to find the answer and I have found that it might be possible but for the life of me I cannot get it to work.
Could somebody please help with what I am doing wrong here:
import static org.junit.Assert.*;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
import static org.hamcrest.Matchers.containsString;
public class Bidder_Home_004 {
private Selenium selenium;
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "URL");
selenium.start();
}
#Test
public void testBidder_Home_004() throws Exception {
// Login
selenium.open("/bidderlogin");
selenium.select("id=ContentPlaceHolder1_ddlBidder", "label=A H Biler");
selenium.click("id=ContentPlaceHolder1_btnLogin");
selenium.waitForPageToLoad("30000");
selenium.click("id=hrefCurrent");
selenium.waitForPageToLoad("30000");
Thread.sleep(3000);
// End Login
// Navigate to Home page
selenium.click("//*[#id='hrefCurrent']");
selenium.waitForPageToLoad("30000");
// End Navigate to Home page
// Find Active Tab
String linkHome = selenium.getText("//li[#class='active']");
assertEquals("Igangværende", linkHome);
// End Find Active Tab
// Get Auction ID
selenium.click("//*[#id='spanWait']");
Thread.sleep(3000);
String linkAuctionlist = selenium.getValue("//*[starts-with(#id, 'liAuction')]/#id");
linkAuctionlist = linkAuctionlist.replace("liAuction", "");
// End Get Auction ID
// Get Vehicle ID
String carsinAuction = selenium.getValue("//*[1][contains(#id,'btnBidUp')]/#id");
carsinAuction = carsinAuction.replace("btnBidUp","");
// End Get Vehicle ID
//Find Original Vehicle Value
String OrgVal1 = selenium.getText("//*[#id='bidvalue_"+carsinAuction+"']");
OrgVal1 = OrgVal1.replace("kr. ", "");
OrgVal1 = OrgVal1.replace(".", "");
int OrgVal2 = Integer.parseInt(OrgVal1);
int nextBid = (OrgVal2 + 1500);
// End Find Original Vehicle Value
// Click AutoBid button
selenium.click("//*[#id='btnProxy"+carsinAuction+"']");
Thread.sleep(2000);
selenium.type("//*[#id='txtProxyBid']", ""+nextBid+"");
((JavascriptExecutor)selenium).executeScript("arguments[0].removeAttribute('disabled','disabled')");
selenium.click("//*[#id='btnSubmit']");
Thread.sleep(2000);
// End Click AutoBid button
// Find New Vehicle Value
String NewVal1 = selenium.getText("//*[#id='bidvalue_"+carsinAuction+"']");
NewVal1 = NewVal1.replace("kr. ", "");
NewVal1 = NewVal1.replace(".", "");
int NewVal2 = Integer.parseInt(NewVal1);
// End Find New Vehicle Value
String fileName = new SimpleDateFormat("ddMMyyyy'Autobid.txt'").format(new Date());
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println(NewVal2);
writer.close();
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
As you can see in the "Click Autobid Button" section I have a line that includes JavascriptExecutor - this is a line that I have found on other forums and within stackoverflow however I have not yet gotten it to work.
When I execute I have the following error:
java.lang.ClassCastException: com.thoughtworks.selenium.DefaultSelenium cannot be cast to org.openqa.selenium.JavascriptExecutor
How to solve this error issue?
For Selenium Webdriver:
Please remove following lines from your code in import section:
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
it causes to some conflicts
The reason is at your wrapper class DefaultSelenium.
for casting to JavascriptExecutor it should be distinct instance of selenium's Driver instance.
And it should looks as follows:
((JavascriptExecutor) DefaultSelenium.getDriverInstance()).executeScript()
For solving casting to JavascriptExecutor you should return explisit instance of driver (Firefox, Chrome, Opera, IE... drivers).
And this method should has signature like following:
class DefaultSelenium {
// all class stuff here
public static RemoteWebDriver getDriverInstance() {
return currentDriverInstance;
}
After you will have correct instance of Selenium RemoteWebDriver you able to cast it to JavascriptExecutor and execute JS script.
BTW:
Using Thread.sleep() is very bad style.
Much better is to use explicit waits - Explicit and Implicit Waits

Selenium Webdriver : Getting NoSuchElementException after switching window

I switch from window A to window B.When i try to perform an action on window B,it throws No such element exception.I am new to selenium webdriver.Please help me out.
My requirement :
1)Go to http://www.kotak.com/bank/personal-banking/convenience-banking/net-banking.html
2)Click on SECURELY LOGIN
3)Switch to the newly opened window and fill username and password in it.Locating username and password on this window throwing error.
My code :
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WindowHandler1 {
public static void main(String args[]) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
driver.get("http://www.kotak.com/bank/personal-banking/convenience- banking/net-banking.html");
Thread.sleep(5000);
driver.findElement(By.xpath(".//*[#id='label-01']/a[1]")).click();
Set<String> windowids = driver.getWindowHandles();
Iterator<String> iter = windowids.iterator();
System.out.println(windowids);
String mainWindowId = iter.next();
String tabedWindowId = iter.next();
Thread.sleep(2000L);
// switching to the new pop up window
driver.switchTo().window(tabedWindowId);
Thread.sleep(20000);
//getting no such element exception upon executing line below
driver.findElement(By.xpath(".//*[#id='Username']")).sendKeys("username");
driver.findElement(By.id("Username")).sendKeys("abc");
}
}
I had a similar problem and noticed that in the list of window handles from selenium, the order is not always the same. So in your code it looks like you are dependent on the last window in the list being the new window, when it may be the first. The solution was to make sure that the window you are trying to switch to is not the same as the current window handle.
You may be getting the NoSuchElement exception because you are not in the right window.

Categories

Resources