how do i click drop down menu using Selenium? - 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();

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

Stale element error while getting text of element

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

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

Selenium WD - southwest.com

I am constantly getting "No Such Element Exception" for "First Name" test box
Below is my code:
public class southwestSignUpSave {
WebDriver oBrw;
#Before
public void loadwebsite (){
oBrw = new FirefoxDriver();
oBrw.manage().window().maximize();
oBrw.get("https://southwest.com");
oBrw.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void signUpAndSave(){
oBrw.findElement(By.partialLinkText("OFFERS")).click();
oBrw.findElement(By.partialLinkText("Sign")).click();
//oBrw.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebDriverWait oWait = new WebDriverWait(oBrw, 30);
oWait.until(ExpectedConditions.presenceOfElementLocated(By.id("FIRST_NAME")));
oBrw.findElement(By.id("FIRST_NAME")).clear();
oBrw.findElement(By.id("FIRST_NAME")).sendKeys("abc");
oBrw.findElement(By.id("LAST_NAME")).clear();
oBrw.findElement(By.id("LAST_NAME")).sendKeys("asd");
oBrw.findElement(By.id("EMAIL")).clear();
oBrw.findElement(By.id("EMAIL")).sendKeys("abc#asd.com");
new Select(oBrw.findElement(By.id("HOME_AIRPORT"))).selectByVisibleText("Akron/Canton, OH - CAK");
oBrw.findElement(By.id("IAN")).click();
}
}
I tried to use id and name.
where am I going wrong. I am new to Selenium WD
U can try finding the element using xpath. For that u need to install the firepath plugin in firefox and then inspect the element using firepath.
oBrw.findElement(By.xpath("copy paste the xpath here")).clear();
I would also recommend loading the driver using System property inside loadwebsite() method.
System.setProperty("webdriver.firefox.driver", "//your driver path");
oBrw=new FirefoxDriver();
if the Sign page opens in a new tab/window then u need to navigate to that tab/window because Selenium by default stays in the opening tab. To navigate u need to add the following lines of code after clicking on "Sign"-
Set<String> s=wd.getWindowHandles();
Iterator<String> it=s.iterator();
it.next();//control goes to 1st default tab
String str=it.next().toString();//control goes to the next tab
oBrw.switchTo().window(str);//driver switches to the new window/tab.
if the element is present inside a frame then also u need to switch to that frame first before finding element inside it. Below is the code-
WebElement web=oBrw.findElement(By.xpath("copy paste your frame xpath"));
oBrw.switchTo.frame(web);
now try to find the element present in the new tab/window.
FIRST NAME input text field is inside iframe. Check the below piece of HTML.
<iframe frameborder="0" src="https://luv.southwest.com/servlet/formlink/f?kOHpjQACAY" onload="scroll(0,0);" verticalscrolling="no" horizontalscrolling="no" scrolling="no" title="Click 'n Save signup form"></iframe>
<html dir="ltr">
<head>
<body>
<p>
<span class="required">*Required</span>
</p>
<div class="clear"></div>
<form id="cnsForm" onsubmit="return validateForm();" action="https://luv.southwest.com/servlet/campaignrespondent" method="POST">
<div class="form_field first_name">
<label for="first_name">
<input id="FIRST_NAME" type="text"=""="" maxlength="25" size="22" name="FIRST_NAME">
</div>
...
Hence selenium is unable to find out the element. Here we need to explicitly switch to iframe as below. Insert below code snippet before you find FIRST_NAME. (You can insert well formatted xpath of iframe. I just grabbed it from firebug.)
WebElement iframeSwitch = oBrw.findElement(By.xpath("/html/body/div[1]/div[3]/div[2]/div[1]/div/div/div[4]/div/div/div/div[3]/iframe"));
oBrw.switchTo().frame(iframeSwitch);
That Text box is inside an iFrame, so you need to switch to that iFrame first then try findElement method to locate textbox.
oBrw.findElement(By.partialLinkText("OFFERS")).click();
oBrw.findElement(By.partialLinkText("Sign")).click();
oBrw.switchTo().defaultContent();
oBrw.switchTo().frame(0);
WebElement id = oBrw.findElement(By.name("FIRST_NAME"));
id.sendKeys("USERNAME");
Hope this helps.

How to locate search links in google in Selenium for testing

I am trying to search Google for Selenium, then run down the list of links by clicking each one, printing the page title, then navigating back.
List<WebElement> linkElements = driver.findElements( **<insert code here>** );
for(WebElement elem: linkElements)
{
String text = elem.getText();
driver.findElement(By.linkText(text)).click();
System.out.println("Title of link\t:\t" + driver.getTitle());
driver.navigate().back();
}
To find the elements, I have tried By.tagName("a") which doesn't work because it gets ALL the links, not just the search ones. Using Firebug, I see that each search link has a class of r used on the header h3, and the a tag nested inside it.
See the following:
<h3 class="r">
<a href="/url sa=t&rct=j&q=selenium&source=web&cd=1&cad=rja&ved=0CC8QFjAA&url=http%3A%2F%2Fseleniumhq.org%2F&ei=y4eNUYiIGuS7iwL-r4DADA&usg=AFQjCNHCelhj_BWssRX2H0HZCcPqhgBrRg&sig2=WBhmm65gCH7RQxIv9vgrug&bvm=bv.46340616,d.cGE" onmousedown="return rwt(this,'','','','1','AFQjCNHCelhj_BWssRX2H0HZCcPqhgBrRg','WBhmm65gCH7RQxIv9vgrug','0CC8QFjAA','','',event)"><em>Selenium</em> - Web Browser Automation
</a></h3>
What code can I insert to make this work?
You have a lot of solution for doing it. There's mine. You keep your way like
// You get all links in a list
List<WebElement> linkElements = driver.findElements(By.xpath("//h3/a"));
// for each element(link) you click() on it
for(WebElement elem: linkElements)
{
elem.click();
// i suggest to put a wait right there
System.out.println("Title of link\t:\t" + driver.getTitle());
driver.navigate().back();
}
i don't know why you were trying to complicate with getText() etc.
Try below New Code
WebDriver driver;
driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.findElement(By.id("gbqfq")).sendKeys("Selenium");
Thread.sleep(1500L);
driver.findElement(By.id("gbqfb")).click();
Thread.sleep(1500L);
List<WebElement> linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for(int i=0;i<=linkElements.size();i++)
{
String text = linkElements.get(i).getText();
driver.findElement(By.linkText(text)).click();
Thread.sleep(2000L);
System.out.println("Title of link\t:\t" + driver.getTitle());
Thread.sleep(2000L);
driver.navigate().back();
linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
}
try searching for this selector:
'.g:nth-child('+clickPosition+') h3.r a'
where "clickPosition" is the SERP result array key. Careful though, google now implements an "onmousedown" event that will change the href attribute to their redirect.