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");
Related
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");
}
}
domImage
I have an AngularJS application we are testing. When using selenium 2.53 the below code worked. When I switched over to selenium 3. This code no longer worked. I tried using the different selectby item value, visibletext without any success. Then I tried using the selenium recorder to see what I could get back that may be useful. I tried the below which was created by the recorder and made changes for it to work in my existing code without success also
//Dropdown Single Select
public static WebElement networkCreateTypeDropDown(WebDriver driver) {
element = driver.findElement(_networkCreateNetworkType);
log.info("Network Profiles Network Type drop-down element found");
return element;
}
public static void selectNetworkCreateTypeDropDown(WebDriver driver, int networkType) throws InterruptedException {
element = networkCreateTypeDropDown(driver);
Select drop = new Select(element);
drop.selectByIndex(networkType);
driver.findElement(By.cssSelector("option[value=\"string:Wifi\"]")).click();
log.info("Network Profiles Network Type drop-down value added" + networkType);
}
Below is the code from the dom for your review. Any help would be greatly appreciated
<select id="sel_networktype" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" value="" ng-selected="true" ng-options="n for n in networkTypes" ng-required="true" name="networkType" ng-model="networkprofile.networkType" selected="selected" required="required">
<option value="?" selected="selected"/>
<option label="None" value="string:None">None</option>
<option label="Wifi" value="string:Wifi">Wifi</option>
<option label="Cellular" value="string:Cellular">Cellular</option>
</select>
This is the selenium recorder code i mentioned.
#Test public void testDropDownJavaTestNG3() throws Exception {
driver.get(baseUrl + "/sx200/angapp/ang.xhtml#/networkprofile");
driver.findElement(By.id("btn_create")).click();
driver.findElement(By.id("networkprofileName")).clear();
driver.findElement(By.id("networkprofileName")).sendKeys("TotalTrax");
new Select(driver.findElement(By.id("sel_networktype"))).selectByVisibleText("Wifi");
driver.findElement(By.cssSelector("option[value=\"string:Wifi\"]")).click();
}
I was able to correct this issue by updating to the latest version of FireFox. At this time it is 50.1.0. With the initial release of Selenium 3.0 I upgraded to the latest release at that time. But a new release is now available. Not having the newest release of FireFox was causing the problem.
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
I am trying to select a value available in a read only drop down and I have tried so many options but still failing to select the desired option. The drop down has two values available ValueOne and ValueTwo. By default the ValueOne is selected and in my case I need to select ValueTwo. I used firebug to get the below code when I click on the drop down and do Inspect Element with firebug
The Code is :
<td class="rcbInputCell rcbInputCellLeft" style="width:100%;">
<input id="ctl00_ContentPlaceHolder1_RadGrid1_ctl00_ctl02_ctl02_EditFormControl_rcbControllerType1_Input" class="rcbInput radPreventDecorate" type="text" readonly="readonly" value="ValueOne" name="ctl00$ContentPlaceHolder1$RadGrid1$ctl00$ctl02$ctl02$EditFormControl$rcbControllerType1" autocomplete="off">
</td>
So far I have tried
1----------
Select DropDown = new Select(driver.findElement(By.id("ctl00_ContentPlaceHolder1_RadGrid1_ctl00_ctl02_ctl02_EditFormControl_rcbControllerType1_Input")));
DropDown.selectByVisibleText("ValueTwo");
and I get an exception as
:org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input"
2------------
WebElement Dropdown = driver.findElement(By.id("ctl00_ContentPlaceHolder1_RadGrid1_ctl00_ctl02_ctl02_EditFormControl_rcbControllerType1_Input"));
Select clickThis = new Select (Dropdown);
clickThis.selectByVisibleText("ValueTwo");
Get Exception:
org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input"
I also tried selectByIndex but still get the above exception message.
3--------------
driver.findElement(By.id("ctl00_ContentPlaceHolder1_RadGrid1_ctl00_ctl02_ctl02_EditFormControl_rcbControllerType1_Input")).sendKeys("ValueTwo");
Nothing happens and the case is marked as Pass. No error no exception.
Also I am running my webscript on firefox 38.0.5 with selenium 2.46.0 with eclipse TestNG.
I have confirmed the frame is not an iframe.
Please suggest the solution.
The root problem might be, that this is not a standard select box but an javascript based solution. The code above just shows the 'host' html element. I am pretty sure that there will be a) a previous hidden element that becomes visible or b) a newly created element in your DOM that holds the values. You have to find those (dev tools or firebug) to interact with.
Some pseudo code that might appear (just to get a hint):
<ul>
<li id="element1">ValueOne</li>
<li id="element2">ValueTwo</li>
</ul>
And after it appears (wait for in selenium) you just have to click the desired element.
Find your xpath through firepath addon in firefox.
driver.findElement(By.xpath(".//*#id='ctl00_ContentPlaceHolder1_RadGrid1_ctl00_ctl02_ctl02_EditFormControl_rcbControllerType1_Input']")).click();
Select value in dropdown ->goto firpath by right click and copy xpath
driver.findElement(By.xpath(".//*#id='ctl00_ContentPlaceHolder1_RadGrid1_ctl00_ctl02_ctl02_EditFormControl_rcbControllerType1_Input']/span[3]")).click();
hope you will find your solution :-)
You can use this :-
driver.findElement(By.id("ctl00_ContentPlaceHolder1_RadGrid1_ctl00_ctl02_ctl02_EditFormControl_rcbControllerType1_Input")).sendKeys("ValueTwo", Keys.ARROW_DOWN, Keys.ENTER)
you can use the following code. Here what I have done is find the dropdown, click on it and find the option to select and send down key until we see the element to select and after click on it.
public class InputDropdownselect {
#Test
public void login() throws Exception
{
System.setProperty("webdriver.chrome.driver", "G:\\drivers\\chrome\\chromedriver_win32\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("https://yourwebsite.com");
driver.manage().window().maximize();
driver.findElement(By.id("txtuser")).sendKeys("123456");
driver.findElement(By.id("txtpassword")).sendKeys("Abc!#1");
driver.findElement(By.id("log-btn")).click();
Thread.sleep(2000);
driver.findElement(By.id("enrollment")).click();
//driver.findElement(By.xpath("//*[#id=\"enrollment\"]")).click();
driver.findElement(By.xpath("//*[#id=\"studentBasicForm\"]/div[2]/div[9]/div/div/input")).click();
Actions action= new Actions(driver);
WebElement joiningYear=driver.findElement(By.xpath("//input[#placeholder=\"Joining Year Group\"]/following::ul[1]/descendant::li/following::span[contains(text(),\"8\")]"));
do {
action.sendKeys(Keys.ARROW_DOWN).perform();
} while (!joiningYear.isDisplayed());
joiningYear.click();
}
}
I am starting in the world of UI automation with WebDriver and Java. I am getting a problem when I try to select a element of a combo box. This is the code:
WebDriver driver = new FirefoxDriver();
driver.get("http://intersite.com/");
new Select(driver.findElement(By.xpath(".//*[#id='term']"))); //Exception happens in this line org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[#id='term']"}
And this is the code in the web site (I use Firepath to know the Xpath):
<select name="term" onchange="getTipDoc('');" id="term" class="termination"><option value="">-- Select an Option --</option>
<option value="OPT1">Option 1</option>
<option value="OPT2">Option2</option>
</select>
I see in the tag select, the ID attribute is correct but the exception always happens. I tried with othe method for locate the element like "By.id" but doesn't work too. What can i do?
Regards!
Couple of possible reasons can happen in case like this
Element you are looking for is inside an iframe. Use driver.switchTo().frame(driver.findElement(somethting));
Element look up is faster than the load time. In this case use explicit wait. WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("term"))); See this
There are duplicate Ids. try using select[id='term'][class='termination'] as cssSelector
And, of course use By.id() since the id is available.
you need to wait to get the page load before trying to get its element this code will help you to do that
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='term']")));