Stale element error while getting text of element - selenium

I want to get the text of li (second) element as below. Code is able to find the element but it is throwing the error while fetching the gettext. Please help.
WebElement element = driver.findElement(By.xpath("//div[contains(#id,'location_group')]/div/ul/li[2]"));
element.getText();
Error
Stale element reference: element is not attached to the page document
HTML
<div id=location_group>
<div>
<ul class="og-tooltip js-og-tooltip" style="display: none; opacity: 100;">
<li class="title_text">Organization Group</li>
<li class="value_text" style="background: rgb(204, 136, 136); border: 2px solid red;">Global / Aricent / gemsecure </li>
<li> </li>
<li class="title_text">Group ID</li>
<li class="value_text">gemsecure</li>
</ul>
</div>
</div>

May be you have to wait for the parent element to be visible then interact with it
WebElement elementUL = driver.findElement(By.xpath("//div[contains(#id,'location_group')]/div/ul"));
WebDriverWait wait=new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOf(elementUL));
WebElement element = driver.findElement(By.xpath("//div[contains(#id,'location_group')]/div/ul/li[2]"));
element.getText();

Because this element is wrapped with a ul that has display: none selenium can not interact with it.
Options to try:
element.getAttribute("innerHTML");
or you can use the JavascriptExecutor:
JavascriptExecutor executor = (JavascriptExecutor)driver;
String text= executor.executeScript("document.document.getElementsByClassName('value_text')[0].innerHTML");
Another option is to use querySelector/querySelectorAll which has broader support than getElementsByClassName

Place a explicit waitWebDriverWait and wait till element to be visible
WebElement ele = driver.findElement(By.xpath("Your locator "));
WebDriverWait wait=new WebDriverWait(driver, 25);
wait.until(ExpectedConditions.visibilityOf(ele));
and then getText()

What I recommend is one use the xPath. I think I've tried every solution in java's selenium library, thus my website had tricky selects - once user picks an option, the options are reloaded (ex. selected value sometimes disappears, sometimes different options where loaded depends on particular select).
Lot of stale element exceptions.
What I've used:
private WebElement getDesiredOptionByVisibleText(WebDriver driver, String selectId, String text) {
List<WebElement> options = driver.findElements(By.xpath("//select[#id='" + selectId
+ "']/option[contains(text(),'" + text + "')]"));
if (options == null || options.size() == 0) {
return null;
} else {
return options.get(0);
}
}
especially use this method with waits, for example my wait:
private void waitUntilDesiredOptionVisible(WebDriver driver, String selectId) {
getFluentWait(driver).until(d -> (getDesiredOptionByVisibleText(driver, selectId, value) != null));
}
public static FluentWait<WebDriver> getFluentWait(WebDriver driver) {
return new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(60))
.pollingEvery(Duration.ofMillis(100));
}
Last but not least clicking that option.
private void selectByVisibleTextRegex(WebDriver driver, String selectId) {
WebElement option = getDesiredOptionByVisibleText(driver, selectId, value);
if (option == null) {
throw new NoSuchElementException(String.format("Cannot locate element with text like: %s.", value));
}
option.click();
}

Related

NoSuchElementException: Unable to locate element uisng selenium web-driver

Here i am trying to click a button using css selector find method.But its unable to locate the element. So i tried giving the time also but still its unable to click the element
Code sample -->
WebDriverWait waitr = new WebDriverWait(driver, 10);
WebElement element = waitr.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#userTable > tbody > tr:nth-child(3) > td.sorting_1 > div > a")));
element.click();
My HTML body Looks as follows
<a data-toggle="dropdown" class="mainAnchor" aria-expanded="false">CA05
<span class="caret" style="margin-left:5px;"><span> </span></span></a>
If i use Thread.sleep(1000); instead of wait it works fine but i don't want to use Thread.sleep.Please help me to solve this issue
To click on the element with text as CA05 you can use the following line of code :
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.mainAnchor[data-toggle=dropdown]"))).click();
Hi you can use a fluentwait like the following below.
static Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(elementWaitTime, SECONDS)
.pollingEvery(2,SECONDS)
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver aDriver) {
driver= aDriver;
element.click();
return aDriver.findElement(cssSelector("#userTab a.mainAnchor"));
}
});

Selenium cannot click menu-item from bootstrap dropdown

Actions action = new Actions(driver);
WebElement we = driver.findElement(By.xpath("//*[#id='ctl00_Sitemap1_HyperLink1']"));
action.moveToElement(we).build().perform();
WebElement tmpElement= driver.findElement(By.xpath("//*[#id='ctl00_Sitemap1_HyperLink1']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", tmpElement);
List<WebElement> dd_list = driver.findElementsByXPath("//*[#id='masterNavigation']/ul/li[1]/ul/li");
for (WebElement ele : dd_list)
{
System.out.println("Values " + ele.getAttribute("innerHTML"));
if (ele.getAttribute("innerHTML").contains("Event Dashboard")) {
ele.click();
break;
}
}
}
Hi I am trying to Automate bootstrap drop-down menu. It's visibility is hidden by default.Once you hover mouse on it, its visibility property shows visible.I am able to click on drop-down , but after clicking on drop-down my selenium script is not selecting value from drop-down.
Error: Exception in thread "main"
org.openqa.selenium.ElementNotVisibleException: Cannot click on
element
HTML Code Snippet
<a class="ui-button-text-icons" id="ctl00_Sitemap1_HyperLink1" href="javascript:void(void);">
<span style="padding-right: 1.3em;">Dashboards</span>
<span class="ui-button-icon-secondary ui-icon ui-icon-triangle-1-s"></span>
</a>
<ul style="visibility: hidden;">
<li class="first featureGranted">
Classic Dashboard
</li>
</ul>
Few things
You don't need to traverse though all li elements to find your desire element you can do it with Xpath
I have no Idea why you are using JavaScript to click first Element, but unless click method provided by Selenium is not working I would suggest not to use JavaScript Click
Error suggests that element is not visible, it could be due to multiple reasons. You could wait using Explicit wait until element is visible as mentioned below. it might resolve your issue
Code
Actions action = new Actions(driver);
WebElement we = driver.findElement(By.xpath("//*[#id='ctl00_Sitemap1_HyperLink1']"));
action.moveToElement(we).build().perform();
WebElement tmpElement= driver.findElement(By.xpath("//*[#id='ctl00_Sitemap1_HyperLink1']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
// I have no idea why you are clicking using JavaScript
js.executeScript("arguments[0].click();", tmpElement);
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement eventDashboardMenu = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[contains(text(),'Event Dashboard')]")));
eventDashboardMenu.click();

Unable to select an item from a hidden RadComboBox

It would be very much helpful if I could get a solution for the below problem.
I'm unable to select an item from a hidden Radcombobox. The below code just enabled the field and I could see the combobox drops down in a fraction of second but the item specified is not selected. Please assist me correcting my code.
HTML Script
<a id="cmb_40_Arrow" style="overflow: hidden;display: block;position: relative;outline: none;">select</a>
Java Code
((JavascriptExecutor)driver).executeScript("arguments[0].click();", getElement("InterPoint")); //This is the combobox field
new FluentWait<WebDriver>(driver)
.withTimeout(1000, TimeUnit.SECONDS).pollingEvery(1, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class)
.until(new Function<WebDriver, Boolean>() {
#NotNull
#Override
public Boolean apply(WebDriver webDriver) {
WebElement element = getElement("CustomerPole"); /*This is the item from the field "Interpoint"*/
return element != null && element.isDisplayed();
}
});
Tried the below code and it doesn't work either
//waitpgm.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(" //*[#id='pnlHeaderInterconnectionPointInformation']"))).click();
//waitpgm.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='cmb_40_DropDown']/div/ul/li[2]"))).click();
//waitpgm.until(ExpectedConditions.elementToBeClickable(getElement("CustomerPole"))).click();

How to print the background colour of a menu item while hovering the mouse using selenium webdriver

I am automating a webpage.I have to check the mouse hover functionality works fine or not.
I have to print the background color when mouse is pointed to a particular item.I have written the code but it does not throw the correct out put.
public class Selenium_Demos extends Environment_Setup {
#Test
public void test() throws Exception {
Rapidaction();
}
private void Rapidaction() throws Exception
{
driver2.get("http://www.rapidvaluesolutions.com/");
Actions builder = new Actions(driver2);
// To click on the link 'PRODUCT'
WebElement td_Home = driver2.findElement(By.xpath("//html/body/section[1]/header/nav/ul/li[1]/a"));
String bgColor = td_Home.getCssValue("background-color");
System.out.println("Before hover: " + bgColor);
builder.moveToElement(td_Home).build().perform();
bgColor = td_Home.getCssValue("background-color");
System.out.println("After hover: " + bgColor);
driver2.quit();
}
}
As we point the mouse over the link'Product', the colour of the link - blue should be printed.
From comment moving to post as I want to post some code.
Can you please change below line
WebElement td_Home = driver2.findElement(By.xpath("//html/body/section[1]/header/nav/ul/li[1]/a"));
To
List<WebElement> td_Home = driver2.findElements(By.xpath("//html/body/section[1]/header/nav/ul/li[1]/a"));
And then check what is the length of td_Home i.e. print "td_Home.size()"
if the length is more than 1 then you have to debug if it is giving the size as 1 then check some attribute of the element to make sure you have selected a proper element.
Please try this.
UPDATE:
Now please do
String bgColor = td_Home.get(0).getCssValue("background-color");
I have created simple example for you:copy this html in some location and save as .html
<html>
<body>
<div id="mydiv" style="width:200px;background:white" onmouseover="this.style.background='gray';" onmouseout="this.style.background='white';">
on mouse over color change.
</div>
</body>
</html>
**web driver code:**
driver.get("file:///C:/Users/vkiran/Desktop/color1.html");
WebElement element = driver.findElement(By.xpath("//*[#id='mydiv']"));
Actions builder = new Actions(driver);
Action mouseOver = builder.moveToElement(element).build();
String bgColor = element.getCssValue("background-color");
System.out.println("Before hover: " + bgColor);
mouseOver.perform();
bgColor = element.getCssValue("background-color");
System.out.println("After hover: " + bgColor);
Identify that webelement, then by help of getAttribute() method find the colour
System.out.println("Hexadecimal color : "+driver.findElement(By.xpath("write the proper xpath")).getAttribute("bgcolor"));
This will give hexadecimal notation for colour
Actions actions = new Actions(driver);
WebElement element = driver.findElement(mycopieslink_locator);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 3px solid red;');", element);
actions.moveToElement(element);
actions.click().build().perform();

how do i click drop down menu using Selenium?

i'm trying to upload some sonar ruleset files to multiple sonars.
i want to get help by web ui automator using Selenium.
i wrote some java code but it still doesn't work.
*added comment
bellowed code works on chrome driver but it doesn't work on safari driver.
please tell me how to modify code to work for multiple browser.
here is my code
public void openQualityProfiles() {
String linkTextSettings = "Settings";
String cssSelector = ".dropdown-menu > ul > li > a";
WebElement settings = waitForElement(By.linkText(linkTextSettings));
settings.click();
WebElement qualityProfiles = waitForElement(By.cssSelector(cssSelector));
qualityProfiles.click();
}
public WebElement waitForElement(By locator) {
WebElement target = null;
WebDriverWait wait = new WebDriverWait(driver, 10);
target = wait.until(ExpectedConditions.elementToBeClickable(locator));
return target;
}
and here is HTML
Settings
<div id="admin-panel" class="dropdown-menu" style="display: none">
<ul>
<li>Quality Profiles</li>
<li>Configuration</li>
<li>Security</li>
<li>System</li>
If your submenu appears when mouse is over, you can use:
new Actions(driver).moveToElement(yourMenu).build().perform();
or try to click on
driver.findElement(By.className("link-more")).click();