Selenium Webdriver : Getting NoSuchElementException after switching window - java

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.

Related

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

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 ?

in selemium webdriver not able to switch over window (i am using java)

this is my code
wait method is not working
switching over windows is not working
please help me to get over this issue
i am using selenium 3.01 jars
import java.util.concurrent.ForkJoinPool.ManagedBlocker;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WindowHandling extends BaseClass
{
public static void main(String args[])
{
System.setProperty("webdriver.gecko.driver",System.getProperty("user.dir")+"\\driver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"\\driver\\chromedriver.exe");
//WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("file://D:/8850OS_Code/Chapter 3/HTML/Window.html");
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
String window1 = driver.getWindowHandle();
System.out.println("First Window Handle is: " + window1);
WebElement link = driver.findElement(By.linkText("Google Search"));
link.click();
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
String window2 = driver.getWindowHandle();
System.out.println("Second Window Handle is: " + window2);
System.out.println("Number of Window Handles so for: "+ driver.getWindowHandles().size());
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
driver.switchTo().window(window1);
System.out.println("task done ");
}
}
thank you
Switching windows doesn't work for you because you are switching to the currently focused (first) window. If you check window1 and window2 values you will see they are the same: the window handle of the first window. To switch to the new window you need to switch to the handle that is different from the current window handle
String window1 = driver.getWindowHandle();
for (String windowHandle : driver.getWindowHandles()) {
if (!windowHandle.equals(window1)) {
driver.switchTo().window(windowHandle);
}
}
String window2 = driver.getWindowHandle(); // now it will be the window handle of the second window
And to close the new window and switch back
driver.close();
driver.switchTo().window(window1);
As for the wait, implicitlyWait is defined one time after creating the WebDriver, it will be valid for the entire life span of th driver and it means the driver will wait up to the specified amount of time until the elements are found when using driver.findElement(). You can see more about waits here.

Handling Light box / Light window in selenium using webdriver

I have been trying to automate a certain flow on a website, but whenever I navigate to the site a light box/window appears because of which my element is not getting selected.
I have tried 2 approaches to close the window but none of them are working:
Have tried to close the window using the pop up closing approach.
Have tried Frames approach but that isn't working as well.
Below is my code:
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Handle_Windows_popUP {
static WebDriver driver = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\Drvier\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://www.makemytrip.com");
Set<String> id = driver.getWindowHandles();
Iterator<String> itr = id.iterator();
System.out.println(id.size());
while(itr.hasNext())
{
Object element = itr.next();
System.out.println("id: "+element);
}
// Trying to find the 'X' button if present in any of the frame but none of the frame has it
List<WebElement> ls = driver.findElements(By.tagName("iframe"));
System.out.println("Numberof frames:"+ls.size());
for(int i=0;i<ls.size();i++)
{
driver.switchTo().frame(i);
System.out.println("Frame: "+i);
System.out.println(driver.findElements(By.xpath("*[#id='htmlDoc']/body/div[13]/div/a[1]")).size());
driver.switchTo().defaultContent();
}
// The Pop-up approach
String parent_Window = itr.next();
String child_win = null;
while(itr.hasNext())
{
child_win = itr.next();
driver.switchTo().window(child_win);
driver.close();
}
driver.switchTo().window(parent_Window).getTitle();
}
}
as this works fine if u refresh the browser, i will suggest u not to use any other code. But if u want to know how to close the window without refresh browser, write the below code after launch:
//wait until the browser loaded.
//than use this code
driver.findElement(By.cssSelector("div.appfest_container.appfest_container-bg.visible-md.visible-lg >a.appfest_container-close.pull-right.clearfix")).click();
my css path is long but u may change it by using xpath.
//*[#id="htmlDoc"]/body/div[13]/div/a[1]
and hope u will accept the answer.

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

Categories

Resources