can´t select dropdown option (selenide/java) - java

I have a little problem selecting options out of drop down lists with selenide (java).
Here's a little snippet of the HTML code and my try to select the option by the value:
HTML snippet
[Java code]
String dateRangeSearchFor = "YESTERDAY";
ElementsCollection ListOfOptions = $(By.id("searchMaskForm:jobSearch_dateRange_input")).$$(By.tagName("option"));
logger.info("selecting option");
for (SelenideElement listElement : ListOfOptions)
{
String valueOfElement = listElement.getAttribute("value");
if (valueOfElement.equals(dateRangeSearchFor))
{
//$(By.xpath("//*[#id='searchMaskForm:jobSearch_dateRange_input']/option[contains(., '"+dateRangeSearchFor+"')]")).setSelected(true);
listElement.setSelected(true); break;
}
}
For some reason the code is not working, neither with the text nor with the index. Any suggestions?
Edit: .click(); and selectOption(); aren't working neither

SelenideElement have method selectOptionByValue(java.lang.String... value)

The piece of code below will help:
String dateRangeSearchFor = "YESTERDAY";
Select select = new
Select($(By.id("searchMaskForm:jobSearch_dateRange_input")));
select.selectByValue(dateRangeSearchFor);
In my case it did.
BTW, if the automation test suite you're creating is a part of automation, that includes functional and load testing, this link will help you to combine those tools in one system, check it out - How to automate Selenium and jmeter testing .

Selenide provides the following methods for a selecting an option in dropdownlist.
selectOptionByValue(value)
selectOption(text)
selectOption(index)
selectOptionContainingText(text)

If you know the index of the element in dropdown menu then you can just use built-in methon selectOption().
It will look like this:
$(CSS-selector).selectOption(index-of-element);
!!REMINDER: CSS-selector MUST point to the <select> element in HTML.

<select class="switch-version" id="switch-version-select" onchange="switchVersionSelect()">
<option value="/v1.x/demo/my_boss_is_in_a_hurry/flexigrid">Flexigrid</option>
<option value="/v1.x/demo/my_boss_is_in_a_hurry/datatables">Datatables</option>
<option value="/v1.x/demo/my_boss_is_in_a_hurry/bootstrap" selected="selected">Bootstrap V3 Theme</option>
<option value="/v1.x/demo/my_boss_is_in_a_hurry/bootstrap-v4">Bootstrap V4 Theme</option>
<option value="/v1.x/demo/my_boss_is_in_a_hurry/bootstrap-v5">Bootstrap V5 Theme</option>
</select>
In the example of the html code above, to select one of the value options with Selenide simply implement the code below.
public class HomePage {
SelenideElement bootstrapElement = $(By.cssSelector("#switch-version-select"));
public void selecionarDropDown(){
$(bootstrapElement).selectOptionContainingText("Bootstrap V4 Theme");
}
}

Related

Selecting dropdown value without ID using Selenium

Got below HTMLcode for dropdown:
<select name="PWCMasterPage$PWCWebPartManager$gwpTemplateFr1$TemplateFr1$drpProductType" id="PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType" tabindex="2" class="PWCDropDownList" profiledatamember="" profileid="TEMPLATE" onblur="this.Holder = GetControlHolder(this);" onchange="this.Holder = GetControlHolder(this);" onfocus="this.Holder = GetControlHolder(this);" data-val-subtype-type="none" controlscollectionname="TemplateFr1_drpProductType" data-configid="TemplateFr1_drpProductType" holdername="TemplateFr1Holder">
<option value=""></option>
<option value="7">Expedited</option>
<option value="8">Premier</option>
<option value="9">Value</option>
</select>
Have been trying to select the dropdown values with:
Select dropDown = new Select(driver.findElement(By.xpath("//*[#id=\"PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType\"]")));
dropDown.selectByValue("8");
Getting below error:
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
Cannot locate option with value: 8
Select dropDown = new Select(driver.findElement(By.xpath("//*[#id=\"PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType\"]")));
dropDown.selectByVisibleText("Expedited");
Which resulted in below error:
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
Cannot locate element with text: Expedited
Have tried alternately with selectByVisibleText and selectByIndex as well which resulted in similar errors.
The issue isn't the java code you provided or the HTML source.
I created a simple web page with your html:
<html><body>
<select name="PWCMasterPage$PWCWebPartManager$gwpTemplateFr1$TemplateFr1$drpProductType" id="PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType" tabindex="2" class="PWCDropDownList" profiledatamember="" profileid="TEMPLATE" onblur="this.Holder = GetControlHolder(this);" onchange="this.Holder = GetControlHolder(this);" onfocus="this.Holder = GetControlHolder(this);" data-val-subtype-type="none" controlscollectionname="TemplateFr1_drpProductType" data-configid="TemplateFr1_drpProductType" holdername="TemplateFr1Holder">
<option value=""></option>
<option value="7">Expedited</option>
<option value="8">Premier</option>
<option value="9">Value</option>
</select>
</body></html>
I created a simple test class - and it works lovely!
Pasting the lot so you can see i do nothing other than open the page, use your code and select the element.
public class StackTest {
private String baseUrl = "C:\\Git\\stackTest.html";
private WebDriver driver;
#Before
public void CreateWebDriver()
{
System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl);
}
#After
public void CloseAndQuitWebDriver() {
driver.close();
driver.quit();
}
#Test
public void approach1_ExistingCode()
{
Select dropDown = new Select(driver.findElement(By.xpath("//*[#id=\"PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType\"]")));
dropDown.selectByValue("8");
}
}
In my opinion, the problem isn't selenium, the problem isn't the xpath, as long as you're doing what #SeleniumUser002 says in his answer then the problem isn't object accessibility.
Have a think about:
What is your site doing that's special?
Is it doing anything script based which creates/populates this drop down at run time?
When you captured the html did you capture it from chrome manually or chromedriver at runtime? (try the latter if you didn't already - Running manually is what a user sees, but chromedriver is what selenium sees. Be careful not to click on anything else other than the object when inspecting so you don't skew the results)
Are you doing any other steps in the script that can influence this dropdown?
First thing i would say to really fixing this issue is to use a breakpoint before your broken line and slowly step though the actions that lead the issue. See if the page is behaving differently at runtime. Walking through slowly also removes synchronisation issues and once the code works once, if it goes back to being flaky you can rule out the code and focus on a better wait strategy.
If that doesn't work and you're STILL seeing all the options present but cannot select, do a dump of what selenium can see:
#Test
public void debug_WhatAreMyOptions()
{
Select dropDown = new Select(driver.findElement(dropdownIdentifier));
System.out.println("dropdown has "+ dropDown.getOptions().size()+" options");
System.out.println("the options are....");
for (var dropdownOptions : dropDown.getOptions()) {
System.out.println(dropdownOptions.getText());
}
}
That might help you actually figure out what's happening to solve the issue.
Without that debugging information no one can tell you what the problem is - but i can suggest work arounds!
Try these...
Set this up:
private By dropdownIdentifier = By.xpath("//*[#id=\"PWCMasterPage_PWCWebPartManager_gwpTemplateFr1_TemplateFr1_drpProductType\"]");
Then try old fashioned clicks without a select object:
public void approach2_Clicks()
{
driver.findElement(dropdownIdentifier ).click(); // to activate
driver.findElement(dropdownIdentifier ).findElement(By.xpath("//*[#value='8']")).click();
}
Or try our old friend javascript:
public void approach3_Javascript()
{
var dropdown = driver.findElement(dropdownIdentifier);
((JavascriptExecutor) driver).executeScript("arguments[0].value='8'", dropdown);
}
However - these work arounds are only possible if the list is populated... My gut tells me that the data isn't there to select at runtime, but as you say it's an internal link so only you can verify that :-)
Give it a go and let us know.
Are you using safari?
If so, there's known issues with webdriver and safari. The long and short of it is to use the driver provided by apple.
This is the selenium issue: https://github.com/SeleniumHQ/selenium/issues/3145
If you look at:
https://webkit.org/blog/6900/webdriver-support-in-safari-10/
They say:
"Safari’s driver is launchable via the /usr/bin/safaridriver
executable, and most client libraries provided by Selenium will
automatically launch the driver this way without further
configuration."
try below solution with WebDriverWait to avoid synchronization issue:
WebDriverWait wait = new WebDriverWait(driver,30);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("PWCDropDownList")));
Select drpCountry = new Select(element);
drpCountry.selectByValue("8");

How can i deselect an option from a dropdown, when that respective dropdown is not a "multi-select" / java & Selenium

I tried to use the objname.deselectByVisibileText() on multiple dropdowns (select/span) and I get the following error
Exception in thread "main" java.lang.UnsupportedOperationException: You may only deselect options of a multi-select.
How can I clear those respective fields? My method atm looks like this:
public void deselect(String s, String t)
{
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(s)));
Select select = new Select(element);
select.deselectByVisibleText(t);
}
Obviously, I need a solution without deselect, as none of them work (byValue, byIndex, etc.) due to the same error as above.
Typically the first option is the default. You can just select it.
select.selectByIndex(0);
If you have a select element that looks like this:
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
Running the code:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex];
would return the selected option.
Now you got to know the selected index. So, use javascript executor to unselect it

How can I click on a particular href in the code below

I am in a situation where there are no unique id and there are number of div's under a class. Cssselector and xpath's are so generic that they are not being recognized.
This is what the Html looks like:
This is my code which doesn't work:
#Test
public void NaviToEpisode(){
driver.findElement(By.linkText("/episode")).click();
title_episode = driver.getTitle();
Assert.assertTrue(title_episode.contains("File uploading"));
}
Please help!
You can use cssSelector, in your case it would be:
driver.findElement(By.cssSelector("#links>div>a").click();
If you use Firefox, install Firebug plugin, then right click on the element you wish to inspect and in menu click on "Inspect with Firebug", once the snippet of your code highlighted right click on it and you should see an option to copy xpath or css.
try this driver.findElement(By.xpath("//*[contains(#href, '/episode/')]")).click();
<div id="links" . . > seems to be static I hope it's unique as well. Following css selector can be used to select first link (i.e. /episodes/)
#links div:nth-child(1) a
Similarly you can use css selectors to select sub-sequent elements. For example to select 2nd element:
#links div:nth-child(2) a
So instead of using By.linkText("/episode"), use By.cssSelector("#links div:nth-child(1) a").

Geb select element that contains something

How do I select the value of a form select field when it has random numbers in its name?
<select name="select_(random numbers)">
<option value="1"></option>
</select>
I have tried:
formValidity {$("form").(contains('validity')) = "1 year"}
which fails.
There are a few ways to achieve this:
formValidity { $("form select[name*='validity']") }
formValidity.value("1 year")
You were trying to use the Geb way.
Geb Selecting Manual
You can also use CSS and jquery selectors which I used above and also prefer.
CSS Selectors
JQuery Selectors

How to retrieve the dynamic value in selenium webdriver

I'm trying to create the test cases using Selenium WebDriver with Java. I have the following HTML syntax in the source.
<label for="00N30000005wfev"><span class=class="requiredMark">*</span>Type</label>
<select id="00N30000005wfev" tabindex="34" name="00N30000005wfev">
<option value="Account">Account</option>
<option value="Client">Client</option>
<option value="Service">Service</option>
</select>
All the "for","id" and "name" value are dynamically generated when the application creates a new item every time. The label name is fixed for the item details. How can I dynamically retrieve this value based on the label name value (e.g. Type)?
When Java runs, it will look at the "Type" label first, then it will be able to find the "for" value.
Thanks
You could use a XPath expression to do this:
WebElement element = driver.findElement(By.xpath("//label[contains(text(),'Type')]"));
String labelForValue = element.getAttribute("for");

Categories