Some links on our page open in a new window using target="_blank". How can I make selenium look at the right window so I can verify that the page is linking to the right page?
Here's what I've been trying:
open /page/
click link=Find us on Facebook!
pause 2000
selectWindow title=window title
verifyTextPresent some text
You don't need to pass a parameter to selectWindow. The browser will automatically give your new window focus, you just need to tell selenium that it's changed. Also make sure you give your new window enough time to actually load before verifying anything:
open /page
click link=Find us on Facebook!
pause 1000
selectWindow
verifyTextPresent some text
$this->click('css=.sf_admin_action_page:first a');
$this->waitForPopUp('_blank');
$this->selectWindow('_blank');
$this->waitForElementPresent('css=.t-info:contains(xxx2)');
// ps. selenium2
you should use selectPopUp to focus the new window. see its document:
selectPopUp:
Arguments:
windowID - an identifier for the popup window, which can take on a number of different meanings
Simplifies the process of selecting a popup window (and does not offer functionality beyond what selectWindow() already provides).
If windowID is either not specified, or specified as "null", the first non-top window is selected. The top window is the one that would be selected by selectWindow() without providing a windowID . This should not be used when more than one popup window is in play.
Otherwise, the window will be looked up considering windowID as the following in order: 1) the "name" of the window, as specified to window.open(); 2) a javascript variable which is a reference to a window; and 3) the title of the window. This is the same ordered lookup performed by selectWindow .
I took slightly different approach which was to force any links to use target = _self so that they could be tested in the same window :
protected void testTextLink(WebDriver driver, final String linkText, final String targetPageTitle, final String targetPagePath) {
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement link = driver.findElement(By.linkText(linkText));
// ensure that link always opens in the current window
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('target', arguments[1]);", link, "_self");
link.click();
wait.until(ExpectedConditions.titleIs(targetPageTitle));
// check the target page has the expected title
assertEquals(driver.getTitle(), targetPageTitle);
// check the target page has path
assertTrue(driver.getCurrentUrl().contains(targetPagePath));
}
Simply use this code.
public void newtab(){
System.setProperty("webdriver.chrome.driver", "E:\\eclipse\\chromeDriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.w3schools.com/tags/att_a_target.asp");
//I have provided a sample link. Make sure that you have provided the correct link in the above line.
driver.findElement(By.className("tryitbtn")).click();
new Actions(driver).sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL).sendKeys(driver.findElement(By.tagName("html")), Keys.NUMPAD2).build().perform();
// In keyboard we will press
//ctrl+1 for 1st tab
//ctrl+2 for 2nd tab
//ctrl+3 for 3rd tab.
//Same action is written in the above code.
}
//Now you can verify the text by using testNG
Assert.assertTrue(condition);
In this Case we can use KeyPress
keyPress(locator, keySequence)
Arguments:
locator - an element locator
keySequence - Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". [Give for CTRL+T]
Simulates a user pressing and releasing a key.
Related
I am clicking with the help of following lione oc code->
actions.moveToElement(objDriver.findElement(By.id("id_popcode")),coordinates.getX(),coordinates1.getY()-1).doubleClick().build().perform();
Basically i double click at a position(x,y) in our application. Individually we cannot click that particular element bcoz it has to be clicked at particular (x,y) itself. So i want to get the properties of that clicked element(which i click using actions command which i mentioned above) liked id, classname. Can some one help me with this...kinda stuck here..........
edit:
try execute.elementFromPoint() with JavascriptExecutor to get element by coordinates
JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement theElement = (WebElement)js.executeScript("return document.elementFromPoint(arguments[0], arguments[1])", coordinates.getX(), coordinates1.getY()-1);
System.out.println(theElement.getAttribute("tagName"));
System.out.println(theElement.getAttribute("class"));
old:
you are using negative value in getY()-1 which mean coordinates above the element, it maybe the parent or preceding-sibling of element try to select it using xpath
WebElement popcodeBefore = objDriver.findElement(By.xpath("//*[#id='id_popcode']/parent::*"));
// Or
// WebElement popcodeBefore = objDriver.findElement(By.xpath("//*[#id='id_popcode']/preceding-sibling::*"));
System.out.println(popcodeBefore.getAttribute("class"));
actions.moveToElement(popcodeBefore).doubleClick().build().perform();
If you have any specific text at that particular coordinates make use of it. I too had the same issue like this where I need to double click on a cell which had text 0.00%. I have done hovering action first using the text and then performed the double-click
Ignore the syntax issues since I am working on the protractor these days
browser.driver.actions().mouseMove(driver.findElement(by.xpath("//*[text()='00')]").build().perform();
and then perform the click
Still, you have issues, check if you have any attribute like ng-click which can be helpful to get the coordinates for that particular location. please always share the HTML code so that It may help us to check more deeply
I am facing an issue where I am unable to locate Element on webpage with any type of locator expect Absolute xpath. Here are details:
URL : https://semantic-ui.com/modules/dropdown.html#selection
Required Element Screen shot:
Manually created Xpath Screen shot( Please note that I am able to recognize Element in web application with manually created xpath but Same xpath is not working in selenium code)
But Same xpath is not working in selenium script.
PLEASE NOTE THAT I AM ABLE TO IDENTIFY SAME OBJECT WITH Absolute xpath
Please help to me to understand reason for this.
Here is code:
public static WebDriver driver;
public static void main(String[] args) {
driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://semantic-ui.com/modules/dropdown.html");
//Selection
driver.findElement(By.xpath("//div[#class='ui selection dropdown upward']")).click();
driver.findElement(By.xpath("//div[#class='menu transition visible']/div[text()='Female']")).click();
System.out.println("Done");
This may be issue with your first x-path. You may try the following code. It may work.
driver.findElement(By.xpath("//div[#class='ui selection dropdown']").click();
driver.findElement(By.xpath("//div[#class='menu transition visible']/div[text()='Male']").click();
You are missing a preceding wildcard in you driver.FindElement XPath.
Instead of driver.findElement(By.xpath("//div..."));, do driver.findElement(By.xpath("//*div..."));.
Currently, what your code is doing is telling the XPath locator to find a first level div (not easily possible, as the first item is almost always the document body), but the wildcard of "*" tells it that it can look for the div at any level.
As an aside, please edit your answer up top with actual code instead of pictures so others with the same problem can find their solution easier.
Longshot:
You are using Chrome to look at the source, but Selenium is using Firefox.
There is a chance that the source is rendered differently between the two browsers. Specifically, your xpath is relying on an exact match of class. I do know that FireFox is notorious for modifying source output.
I haven't done any testing but I would not be surprised if the class is in a different order and it's failing on an exact match.
There are two solutions if that is the case:
Don't do a single exact match (xpath = "") but instead do a mix of contains joined with && (contains ui && contains selection && dropdown)
Don't rely on the output from the console tab. Instead "View Page Source" and view what is actually being sent instead of what is being interpreted by the browser
Find the dropdown container element firstly, then use it to find self descendant, like option etc.
driver.get("https://semantic-ui.com/modules/dropdown.html");
// find dropdown container element
WebElement dropdownWrapper = driver.findElement(
By.xpath("//div[#class='html']/div[input[#name='gender']]"));
// expand drop down options by click on the container element
dropdownWrapper.click();
// or click the down arrow
dropdownWrapper.findElement(By.css('i')).click();
// select option
dropdownWrapper.findElement(By.xpath(".//div[text()='Female']")).click();
To locate the element with text as Gender and select the option Female you can use the following Locator Strategy :
Code Block :
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://semantic-ui.com/modules/dropdown.html#selection");
driver.findElement(By.xpath("//div[#class='another dropdown example']//div[#class='ui dropdown selection']")).click();
driver.findElement(By.xpath("//div[#class='another dropdown example']//div[#class='ui dropdown selection active visible']//div[#class='menu transition visible']//div[#class='item' and contains(.,'Female')]")).click();
System.out.println("Gender Female selected.");
Console Output :
Gender Female selected.
This might be helpful to clearify how selectors are working in general:
.(dot): Dot at starting represents the current node. It tells us that the processing will start from the current node.
. .(double dot): It will select parent of current node. For example, //table/. . will return div element because div is the parent of table element.
‘*’: is used to select all the element nodes descending from the current node. For example:
/table/*: It will select all child elements of a table element.
//*: It will select all elements in the document.
//*[#id = ‘username’]: It will select any element in document which has an attribute named “id” with the specified value “username”.
#: It represents an attribute which selects id, name, className, etc. For example:
#id: It will select all elements that are defined with the id attribute in the document. No matter where it is defined in the document.
//img/#alt: It will select all the img elements that are defined with the #alt attribute.
//td[#*]: It will select all td elements with any attribute.
Here is a link to the article:
https://www.scientecheasy.com/2020/07/selenium-xpath-example.html/
Issue - Getting 'Element is no longer attached to the DOM'
Approach -
1. Check if the element is displayed on the webpage
2. Trying to click the element
Code -
System.out.println("boolean value of Confirm order is" +driver.findElement(By.id("confirmOrder")).isDisplayed());
if (driver.findElement(By.id("confirmOrder")).isDisplayed() == true) { driver.findElement(By.id("confirmOrder")).click();
//driver.findElement(By.id("confirmOrder")).sendKeys("{Enter}");
//actions.moveToElement(driver.findElement(By.id("confirmOrder"))).build().perform();
//actions.click().perform();
System.out.println("button clicked");
}
Output
boolean value of Confirm order istrue
button clicked
Tried couple of approaches but none seems to be working. Any help is appreciated.
I think you are not using implicit or explicit waits, refer this for more info,a very neat explanation is provided on this issue...
On Windows 7, certain web elements such as button doesn’t gets clicked using the below line of code:-
driver.findElement(By.id("ButtonID")).click();
Tried using XPath as well but that didn’t used to work always.
Following is the thread that list down the issue with Windows 7: https://code.google.com/p/selenium/issues/detail?id=6112
This is the workaround:-
WebElement element = driver.findElement(By.id("ButtonID"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
In our application when I mouse over a menu item, drop down appears, where I want to select an item by clicking on it. The structure of the menu is as follows,
Main Menu
Admin Sub menu:
Manage Channels
Manage Users
In selenium webdriver, I tried to click directly on Manage Channels by giving the xpath, linktext, partial link text. But in options it says unable to locate element. I'm attaching a screen shot for reference
driver.findElement(By.linkText("Manage Channels")).click();
driver.findElement(By.xpath("//li/a[contains(., \"Manage Channels\")]")).click();
driver.findElement(By.partialLinkText("Manage Channels"));
Basically, you'll have to first move mouse to 'Menu item' drop-down and then move mouse to option which you want to select and then click on option.
For Ruby following is one line code:
driver.action.movet_to(el1).movet_to(el2).click.perform
I don't know about Java but you can apply above logic. I tried with following Java code, see if it works or modify it wherever required:
WebElement element1 = driver.findElement(By.linkText("Manage Channels"));
WebElement element2 = driver.findElement(By.xpath("//li/a[contains(., \"Manage Channels\")]"))
Actions action = new Actions(driver);
action.moveToElement(element1).moveToElement(element2).click().build().perform();
You can use following methods to hover your mouse on intended menu item:
el = driver.find_element(:id, "some_id")
driver.action.move_to(el).perform'
el = driver.find_element(:id, "some_id")
driver.action.move_to(el, 100, 100).perform
For more guidelines please refer this link : http://selenium.googlecode.com/svn/trunk/docs/api/rb/Selenium/WebDriver/ActionBuilder.html#move_to-instance_method
Hope this will help you !!!
Cheers...
I am submitting search criteria through form to third party URL. I tried to give target="someName". But when i am trying to focus on new window using "sameName" and validating some text there, selenium unable to find that locator or focus on that window. retuning false. please help on this. its urgent.
I also tried storeAllWindowNames or Ids selenium commands, also not working its returning main window ID instead of new open window.
the idea is in the following. as you try to validate some text in a new window, I do not see any necessity to get window name as you are able to get the xpath or cssselector of the text to be validated using firepath (firebug addon in ffox) and using command
String txt = driver.findElement(By.xpath(//...blablbalba)).getText().trim();
//or
String txt = driver.findElement(cssSelecot(html>..blalblabla...)).getText().trim();
//validation
Assert.assertTrue(txt.equals("blablabla"));
you can actually validate it.
or if you want to validate something and selenium is not able to cope with it then I recommend you to use js (getText using js):
String cssSelector=....
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x = $(\""+cssSelector+"\");");
stringBuilder.append("return x.text().toString();") ;
String res= (String) js.executeScript(stringBuilder.toString());
Assert.assertTrue(res.trim().contains("blablabla....") );
Hope this works for you.
This is the solution:
Well, if you have no choice but use it. Here is one solution:
if you have a target with your own name like target="popup", then you only need open the target window before click on the link. Example:
[b]store "javascript{selenium.browserbot.getCurrentWindow().open('', 'popup')}", "myWindow"[/b]
If you have a target="_blank", you need change the target before open the window.
store "javascript{this.page().findElement('link=My link who open the popup with target blank').target='popup'}", "myVar"
store "javascript{selenium.browserbot.getCurrentWindow().open('', 'popup')}", "myWindow"
Then, you click on the link and selectWindow("popup"). That is.
Another solution is rewrite the entire A tag and change the href/target by a javascript window.open but this is a litle more work to do.