Element is no longer attached to the DOM - for a Button - selenium

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);

Related

How to get the clicked element in selenium when we don't know what are we clicking

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

Can't select option: element is found but invisible

I'm trying to automate a website which is not under my control, so I can't change its HTML and CSS. I need to select an option from a combo box.
I can successfully find a "select ../>" element but when I try to select an option via SelectByText, ByValue, ByIndex it results in the ElementNotVisibleException. The html is pretty complex on that page and I believe that developers assigned "display:none" by a css-style. I can navigate to the "div" which contains that combo box and click on it via Actions but it doesn't help to select an option after that. After such a click I see for a second the options on the screen and then the combo box collapses.
Is it possible at all to overcome such a problem?
Since Selenium API tries to be "user-centric" it will not allow interaction with non-visible elements. There are two approaches you can try:
1) Click on the select element, then perform an explicit wait for the option to become visible. This is useful if the page is using JavaScript to display the select options which can cause slight delay.
By bySelect = By.id("id_of_select_element");
By byOption = new ByChained(bySelect, By.xpath(".//option[contains(text(), 'text_of_option')]");
WebElement select = driver.findElement(bySelect);
select.click();
try {
// wait at-most 5 seconds for element to become visible
WebElement option = new WebDriverWait(driver, 5)
.until(ExpectedConditions.visibilityOfElementLocated(byOption)));
} catch(TimeoutException t) {
System.err.println("Timed out while waiting for dropdown to become visible: " + byOption.toString());
}
2) If the above doesn't work, you can be a little more invasive and execute some JavaScript to force the option to be selected. This is only recommended as a last resort.
public void selectDropdownByText(WebDriver driver, WebElement select, String text) {
((JavascriptExecutor) driver).executeScript(
"var select = arguments[0]; for(var i = 0; i < select.options.length; i++) {if(select.options[i].text == arguments[1]) {select.options[i].selected = true; }}", select, text);
}
ok, Element is not visible exception is thrown because of "user-centric" behavior of selenium,
In my working experience i found out that,
Selenium is not able to select element which are not visible to clients.
I mean can't select those who not appears on UI Window,
Still those are you can inspect on HTML DOM but cant access through selenium.
When those are visible on screen you can very well select those elements.
solution is before finding out select tag you must click on it to get visible full options tags.
Clicking makes all options that needs to be selected are now visible to clients.
Then you find that select element and then select options under select tag. when those List of options are completely visible on screen.

selenium webdriver code to click on 'Album' in facebook

I am not able to click on 'Albums' in Facebook.
The HTML is Albums how to locate the element 'Albums' in selenium web driver.
I tried with using driver.findelement(By.xpath(span[#class="_3sz"]) showing error as element not found
And, the html looks the following:
<span class="_3sz">Albums</span>
If I am understanding your problem correctly then that xpath you mentioned returns more than one elements. Use a text based search which is more easier and specific.
driver.findelement(By.xpath("//*[.='Albums']").click();
And, here . is used to directly point to the parent element. Additional wait might be needed to wait for the element to interact. Also, I am assuming you are trying to click the element.
EDIT
Driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10));
Driver.Navigate().GoToUrl("http://www.facebook.com");
Driver.Manage().Window.Maximize();
Driver.FindElement(By.CssSelector("#email")).SendKeys("your email");
Driver.FindElement(By.CssSelector("#pass")).SendKeys("your pass");
Driver.FindElement(By.CssSelector("[type='submit'][value='Log In']")).Click();
Driver.FindElement(By.CssSelector(".fbxWelcomeBoxName")).Click();
Driver.FindElement(By.XPath("//*[.='Photos']")).Click();
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[.='Albums']")));
Driver.FindElement(By.XPath("//*[.='Albums']")).Click();
By albumname = By.XPath("//strong[.='2014']"); //this should be your album name. In my case it's 2014
wait.Until(ExpectedConditions.ElementExists(albumname));
Driver.FindElement(albumname).Click();
wait.Until(ExpectedConditions.ElementExists(By.CssSelector(".fbPhotoAlbumHeader.fbPhotoAlbumOptionsPresent [type='file']")));
Driver.FindElement(By.CssSelector(".fbPhotoAlbumHeader.fbPhotoAlbumOptionsPresent [type='file']")).SendKeys(#"D:\Users\Saifur\Desktop\FacebookPicture\150232_585410621540701_1836495431_a.jpg");
wait.Until(ExpectedConditions.ElementExists(By.CssSelector(".pvm.phl.footerBox.uiBoxWhite")));
Driver.SwitchTo().ActiveElement();
wait.Until(ExpectedConditions.ElementExists(By.CssSelector("[name='postPhotosButton']")));
Driver.FindElement(By.CssSelector("[name='postPhotosButton']")).Click();
Notice mine is C#
It always best practice to follow this sequence while selecting elements.
1) ID
2) CSS
3) XPath (This will have some issues with different browsers specially IE)
In this case, considering this is no other span class with same name. It would have work like this "span._3sz". Simple and powerful.

how to locate an element to perform a click

I'm trying to navigate in site: http://startupnationbook.com/startup-map
I want to click on link of Startups, however I'm not able to locate the element.
I tried:
elem = driver.findElement(By.xpath("//a[contains(text(),'Startups')]"));
and
elem = driver.findElement(By.xpath("//*[#id='listtoggle' and contains(text(),'Startups')]"));
In both cases I get: "Unable to locate element" error
What is wrong in my expressions and how can I locate the element to perform a click.
The map is in an iframe, you're probably not telling Selenium to look in there. I would also look for the span tag, and since the id listtoggle is used many times (poor design, making it worthless), just look for contains Startups.
// Also should probably use a wait here, in case the page takes too long to load
chromeDriver.switchTo().frame(chromeDriver.findElement(By.tagName("iframe")));
WebElement elem = chromeDriver.findElement(By.xpath("//span[contains(text(),'Startups')]"));
You can do like below :
WebDriver driver = new FirefoxDriver();
driver.get("http://startupnationbook.com/");
driver.findElement(By.xpath(".//*[#id='main-nav']/li[5]/a")).click();
Hope this will work. I have tested.

How to verify a target="_blank" link using selenium?

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.