Selenium unable to detect UI element in another tab - java

I am trying to automate a scenario where when I click on a link another tab opens with details.
Question 1 : Do I have to specifically set my focus to the 2nd tab or selenium automatically finds the element in the 2nd tab?
I am using the below code to set the focus to the 2nd tab :
String currentWindow = driver.getWindowHandle();
driver.switchTo().window(currentWindow);
Problem : I am getting an error that selenium is unable to find the specified element.
Could you guys suggest me what am I doing wrong, and the best way to switch to 2nd tab.

Actually, you are setting the focus on the first tab, not the second one. You need to do something like this
String currentWindow = driver.getWindowHandle();
// open the new tab here
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(currentWindow)) {
driver.switchTo().window(handle);
}
}
And the answer to your question is yes, you have to tell the driver to set its focus on the new tab.

You can get all the window handles as handlers=driver. GetWindowHandles() which will return all the handler string. Then using index switch to the appropriate handle using driver.switchto().window(handlers[1])

Related

How to get Handle of the Focused Tab in Selenium?

I am using Selenium for Scrapping purpose for Job Website scrapping. I am ctrl+clicking on jobs to go to second page and scrape details, I somehow wish to keep track of where I clicked to which tab opened up (using a map).
But as soon as I ctrl+click an element, new tab opens and focus changes to that.
How do I get handle of the current focused tab in Selenium
I tried
webDriver.getWindowHandle()
But it returns me the handle for main tab that I ctrl+clicked an element from.
My Full Code
private void openAndMapJobTabs(WebElement jobList) {
List<WebElement> jobRowsSelector = jobList.findElements(By.tagName("article"));
for (WebElement jobRow : jobRowsSelector) {
try {
ctrlClickElement(jobRow);
Thread.sleep(4000);
//the next line is expected by me to give handle of current focused tab
System.out.println(webDriver.getWindowHandle()); // but this gives me handle of main tab
webElementToTabMapper.put(jobRow, webDriver.getWindowHandle());
webDriver.switchTo().window(websiteTabHandle);
} catch (Exception e) {
logger.info("Could Not Click Open Job Tab: "+e.getMessage());
}
}
}
UPDATE
Actually for me, I need to map elements to the tab they open, so order of tabs are important for me, so I purposely need the handle of current focused tab so I can map it with the element which opened that. But by iterating through all handels, I might mess up the order if any one of the webElement fails to open a new tab or if click is disabled on that.
Any help world be highly appreciated.
Also if there are faster and better tools for scrapping, please recommend.
You have to get the handles of those two tabs or windows, then you have to iterate and switch to the newly opened tab. Try the below code:
// This line will get the handles of the all the tabs or windows and store in a var with type 'Set'
Set<String> windowHandles = driver.getWindowHandles();
// Iterating through the Set - i.e., window handles and switch to the other tab
for (String handle : windowHandles) {
// System.out.println(handle);
driver.switchTo().window(handle);
System.out.println("Title: " + driver.getTitle());
}
If you have more than two tabs or windows, then put the above code the in a method, pass the window title which you want to switch as a parameter, and compare the title with each window title, once you switch to the expected window, break.

Selenium: How can I navigate back to parent window

I am running below java code for switching windows and getting error message, Kindly suggest something.
Driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
Set<String>set=Driver.getWindowHandles();
Iterator<String> It=set.iterator();
String PId=It.next();
String CId=It.next();
Driver.switchTo().window(CId);
Driver.get("https://www.facebook.com");/* Here again I want to come back to parent window and perform some action */
Please refer to this java documentation link for the list of available switchTo options:
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/WebDriver.TargetLocator.html
In your case, you may need to save the window handle before switching and then use it later to switch back to original window.
String originalWindow = Driver.getWindowHandle();
Driver.switchTo().window(CId);
//Operations on new window here
Driver.switchTo().window(originalWindow);
//Operations on original window here

Handle Window Pop Up in Selenium

I am working with Selenium, now there is a condition:
when I hit a button in my webpage a window pop up opens up.
Now I have to click a radio button (one out of two, it will work even if we send a TAB ) and then click an OK button. I searched in the net and got to know about "driver.getWindowHandle()".
But I don't have any idea dealing with the newly opened window popup.
Need help in this.
For switching purpose u can use enhanced for loop:
for (String winHandle : objDriver.getWindowHandles()) {
objDriver.switchTo().window(winHandle);
}
So it will switch the control from one driver window to child windows.
To interact with elements on the window try to find element with whatever tool u r using and perform the required action after switching to the window.
To return back to parent window you can use the same loop or use:
driver.switchTo().defaultContent();
Check my answer in this post and also read the comments to help you understand the difference between getWindowHandle() and getWindowHandles()
Java: focus is not on pop-window during window handling
We handled this situation using AutoItX - https://www.autoitscript.com/site/ in our Windows/IE C# project:
AutoItX3 autoIt = new AutoItX3();
var handle = autoIt.WinWaitActive("[window title]", "", 20);
Assert.IsTrue(handle != 0", string.Format("Was not able to find: {0}", [window title]);
autoIt.Send("{ESCAPE}"); // tab may work as well for selection
The pop up was a Windows window, and not part of IE, therefore the WebDriver didn't know about it.
Hope this helps.

Open link in new tab [duplicate]

I have trawled the web and the WebDriver API. I don't see a way to open new tabs using WebDriver/Selenium2.0 .
Can someone please confirm if I am right?
Thanks,
Chris.
P.S: The current alternative I see is to either load different urls in the same window or open new windows.
There is totally a cross-browser way to do this using webdriver, those who say you can not are just too lazy. First, you need to use WebDriver to inject and anchor tag into the page that opens the tab you want. Here's how I do it (note: driver is a WebDriver instance):
/**
* Executes a script on an element
* #note Really should only be used when the web driver is sucking at exposing
* functionality natively
* #param script The script to execute
* #param element The target of the script, referenced as arguments[0]
*/
public void trigger(String script, WebElement element) {
((JavascriptExecutor)driver).executeScript(script, element);
}
/** Executes a script
* #note Really should only be used when the web driver is sucking at exposing
* functionality natively
* #param script The script to execute
*/
public Object trigger(String script) {
return ((JavascriptExecutor)driver).executeScript(script);
}
/**
* Opens a new tab for the given URL
* #param url The URL to
* #throws JavaScriptException If unable to open tab
*/
public void openTab(String url) {
String script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a";
Object element = trigger(String.format(script, url));
if (element instanceof WebElement) {
WebElement anchor = (WebElement) element; anchor.click();
trigger("var a=arguments[0];a.parentNode.removeChild(a);", anchor);
} else {
throw new JavaScriptException(element, "Unable to open tab", 1);
}
}
Next, you need to tell webdriver to switch its current window handle to the new tab. Here's how I do that:
/**
* Switches to the non-current window
*/
public void switchWindow() throws NoSuchWindowException, NoSuchWindowException {
Set<String> handles = driver.getWindowHandles();
String current = driver.getWindowHandle();
handles.remove(current);
String newTab = handles.iterator().next();
locator.window(newTab);
}
After this is done, you may then interact with elements in the new page context using the same WebDriver instance. Once you are done with that tab, you can always return back to the default window context by using a similar mechanism to the switchWindow function above. I'll leave that as an exercise for you to figure out.
The Selenium WebDriver API does not support managing tabs within the browser at present.
var windowHandles = webDriver.WindowHandles;
var script = string.Format("window.open('{0}', '_blank');", url);
scriptExecutor.ExecuteScript(script);
var newWindowHandles = webDriver.WindowHandles;
var openedWindowHandle = newWindowHandles.Except(windowHandles).Single();
webDriver.SwitchTo().Window(openedWindowHandle);
I had the same issue and found an answer. Give a try.
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_T);
It will open a new tab you can perform your actions in the new tab.
Though there is no API for opening a new tab, you can just create a new instance of WebDriver calling it something slightly different and passing the URL you want in the new tab. Once you have done all you need to do, close that tab and make the new driver NULL so that it does not interfere with the original instance of Webdriver. If you need both tabs open, then ensure you refer to the appropriate instance of WebDriver. Used this for Sitecore CMS automation and it worked.
Thanks for the great idea #Jonathan Azoff !
Here's how I did it in Ruby:
def open_new_window(url)
a = #driver.execute_script("var d=document,a=d.createElement('a');a.target='_blank';a.href=arguments[0];a.innerHTML='.';d.body.appendChild(a);return a", url)
a.click
#driver.switch_to.window(#driver.window_handles.last)
end
There's no way we can create new TAB or handle tabs using web driver / selenium 2.0
You can open a new window instead.
Hey #Paul and who ever is having issue opening a second tab in python. Here is the solution
I'm not sure if this is a bug within the webdriver or because it isn't compatible yet with mutlitab but it is definitely acting wrong with it and I will show how to fix it.
Issue:
well I see more than one issue.
First issue has to do that when you open a 2nd tab you can only see one handle instead of two.
2nd issue and here is where my solution comes in. It seems that although the handle value is still stored in the driver the window has lost sync with it for reason.
Here is the solution by fixing the 2nd issue:
elem = browser.find_element_by_xpath("/html/body/div[2]/div[4]/div/a") #href link
time.sleep(2)
elem.send_keys(Keys.CONTROL + Keys.RETURN + "2") #Will open a second tab
#solution for the 2nd issue is here
for handle in browser.window_handles:
print "Handle is:" + str(handle) #only one handle number
browser.switch_to_window(handle)
time.sleep(3)
#Switch the frame over. Even if you have switched it before you need to do it again
browser.switch_to_frame("Frame")
"""now this is how you handle closing the tab and working again with the original tab"""
#again switch window over
elem.send_keys(Keys.CONTROL + "w")
for handle in browser.window_handles:
print "HandleAgain is:" + str(handle) #same handle number as before
browser.switch_to_window(handle)
#again switch frame over if you are working with one
browser.switch_to_frame("Frame")
time.sleep(3)
#doing a second round/tab
elem = browser.find_element_by_xpath("/html/body/div[2]/div[4]/div/a") #href link
time.sleep(2)
elem.send_keys(Keys.CONTROL + Keys.RETURN + "2") #open a 2nd tab again
"""Got it? find the handle, switch over the window then switch the frame"""
It is working perfectly for me. I'm open for questions...
Do this
_webDriver.SwitchTo().Window(_webDriver.WindowHandles.Where(x => x != _webDriver.CurrentWindowHandle).First());
or Last() etc.
PS there is no guarantee that the WindowHandles are in the order displayed on your browser, therefore, I would advise you keep some history of current windows before you do the command to that caused a new tab to open. Then you can compare your stored window handles with the current set and switch to the new one in the list, of which, there should only be one.
#Test
public void openTab() {
//Open tab 2 using CTRL + t keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
//Open URL In 2nd tab.
driver.get("http://www.qaautomated.com/p/contact.html");
//Call switchToTab() method to switch to 1st tab
switchToTab();
}
public void switchToTab() {
//Switching between tabs using CTRL + tab keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
//Switch to current selected tab's content.
driver.switchTo().defaultContent();
}
we can use keyboard events and automate opening and switching between multiple tabs very easily. This example is refered from HERE
I must say i tried this as well, and while it seemingly works with some bindings (Java, as far as Jonathan says, and ruby too, apparently), with others it doesnt: selenium python bindings report just one handle per window, even if containing multiple tabs
IJavaScriptExecutor is very useful class which can manipulate HTML DOM on run time through JavaScript, below is sample code on how to open a new browser tab in Selenium through IJavaScriptExecutor:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
object linkObj = js.ExecuteScript("var link = document.createElement('a');link.target='_blank';link.href='http://www.gmail.com';link.innerHTML='Click Me';document.getElementById('social').appendChild(link);return link");
/*IWebElement link = (IWebElement)linkObj;
link.Click();*/
browser.Click("//*[#id='social']/a[3]");
Just to give an insight, there are no methods in Selenium which would allow you to open new tab, the above code would dynamically create an anchor element and directs it open an new tab.
You can try this way, since there is action_chain in the new webdriver.
I'm using Python, so please ignore the grammar:
act = ActionChains(driver)
act.key_down(Keys.CONTROL)
act.click(link).perform()
act.key_up(Keys.CONTROL)
For MAC OS
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://google.com")
body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.COMMAND + 't')
Java Robot can be used to send Ctrl+t (or Cmd+t if MAC OS X) as follows:
int vkControl = IS_OS_MAC ? KeyEvent.VK_META : KeyEvent.VK_CONTROL;
Robot robot = new Robot();
robot.keyPress(vkControl);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(vkControl);
robot.keyRelease(KeyEvent.VK_T);
A complete running example using Chrome as browser can be forked here.
I would prefer opening a new window. Is there really a difference in opening a new window vs opening a new tab from an automated solution perspective ?
you can modify the anchors target property and once clicked the target page would open in a new window.
Then use driver.switchTo() to switch to the new window. Use it to solve your issue
Instead of opening new tab you can open new window using below code.
for(String childTab : driver.getWindowHandles())
{
driver.switchTo().window(childTab);
}

Set focus on WebElement?

i'm currently testing the GUI of my application, and i wanted to know if it's possible to set the focus to a WebElement ?
I'm using Selenium 2.0 and the webdriver.
So i'm looking for something like that : driver.findElement(xxxx).setfocus();
Thank you.
EDIT :
I've alreardy tested that kind of tricky things
// getting the element WebElement
eSupplierSuggest = driver.findElement(By.xpath("..."));
//get le location and click
Point location = eSupplierSuggest.getLocation();
new Actions(driver).moveToElement(eSupplierSuggest, location.x, location.y).click();
//or
//directly perform
new Actions(driver).moveToElement(eSupplierSuggest).click().perform();
i red somewhere that the click focus the element, but in my case, nothing works. lol
PS : this is a sub-question of that original post Click on a suggestbox, webdriver
I normally send an empty key to the element so it gets focused. So for example:
element.send_keys ""
In order to set focus on the element you can use executeScript method as described below :
JavascriptExecutor js;
js.executeScript ("document.getElementById('x').focus()");
Once the focus is set you can easily use send_keys provided by webdriver api.
Try using cssSelector for the autosuggestion click as shown below and let me know if you are still facing the issue.
// supplier ops, i find and type data into the input
WebElement eSupplier = driver.findElement(By.id("supplier:supplierOps_input"));
eSupplier.sendKeys("OPS1");
sleep(5); // wait the suggestbox
// i find the suggestbox
WebElement eSupplierSuggest = driver.findElement(By.cssSelector("css path of that specific value in the auto suggestion box"));
eSupplierSuggest.click();
sleep(5); // wait the refresh for the next field supplierAddress
There is no function in the WebDriver API to set focus on an element.
If you want to do it you would have to write some JavaScript to set focus and then use a JavaScriptExecutor to run the JavaScript.
Make sure, that you are not changing the frame....
Other wise .click() should do the trick

Categories