I have the task to click on element in the droplist, using exactly Select class.
So I have the HTML block:
<div id="_desktop_currency_selector">
<div class="currency-selector dropdown js-dropdown open">
<span>Валюта:</span>
<span class="expand-more _gray-darker hidden-sm-down" data-toggle="dropdown">UAH ₴</span>
<a data-target="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" class="hidden-sm-down">
<i class="material-icons expand-more"></i>
</a>
<ul class="dropdown-menu hidden-sm-down" aria-labelledby="dLabel" style="display: block;">
<li>
<a title="Евро" rel="nofollow" href="http://prestashop-automation.qatestlab.com.ua/ru/?SubmitCurrency=1&id_currency=2" class="dropdown-item">EUR €</a>
</li>
<li class="current">
<a title="Украинская гривна" rel="nofollow" href="http://prestashop-automation.qatestlab.com.ua/ru/?SubmitCurrency=1&id_currency=1" class="dropdown-item">UAH ₴</a>
</li>
<li>
<a title="Доллар США" rel="nofollow" href="http://prestashop-automation.qatestlab.com.ua/ru/?SubmitCurrency=1&id_currency=3" class="dropdown-item">USD $</a>
</li>
</ul>
<select class="link hidden-md-up">
<option value="http://prestashop-automation.qatestlab.com.ua/ru/?SubmitCurrency=1&id_currency=2">EUR €</option>
<option value="http://prestashop-automation.qatestlab.com.ua/ru/?SubmitCurrency=1&id_currency=1" selected="selected">UAH ₴</option>
<option value="http://prestashop-automation.qatestlab.com.ua/ru/?SubmitCurrency=1&id_currency=3">USD $</option>
</select>
</div>
</div>
In follow attempt, I have
org.openqa.selenium.TimeoutException: Expected condition failed:
waiting for element to be clickable: By.xpath:
//*[#id='_desktop_currency_selector']//select (tried for 30 second(s)
with 500 MILLISECONDS interval)
click(currencyDropListBtn);
WebElement dropListBtn = driver.findElement(By.xpath("//*[#id='_desktop_currency_selector']//i"));
waitToBeClickable(dropListBtn);
dropListBtn.click();
WebElement dropListElement = driver.findElement(By.xpath("//*[#id='_desktop_currency_selector']//select"));
waitToBeClickable(dropListElement);
Select select = new Select(dropListElement);
select.selectByIndex(1);
It will be work in the follow way:
WebElement dropListBtn = driver.findElement(By.xpath("//*[#id='_desktop_currency_selector']//i"));
waitToBeClickable(dropListBtn);
dropListBtn.click();
WebElement dropListElement = driver.findElement(By.xpath("//a[#title='Евро']"));
waitToBeClickable(dropListElement);
click(dropListElement);
But I need to use exactly Select class.
How to correctly select the droplist element via Select?
Normally for select element, you do not need to click the option inside it.
You can just set the value of the select element with value of the option you want to select.
I post a utility function that I use a lot.
set_value("//select[#class='link hidden-md-up']",'http://prestashop-automation.qatestlab.com.ua/ru/?SubmitCurrency=1&id_currency=3','value')
def set_value(xpath, val, field):
script = """(function()
{
node = document.evaluate("%s", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (node==null)
return '';
node.%s='%s';
return 'ok';
})()"""%(xpath,field,val)
driver.execute_script(script)
Related
driver.findElement(By.xpath("//*[#id=\"_desktop_currency_selector\"]/div")).click();
List<WebElement> list = driver.findElements(By.xpath("//*[#id=\"_desktop_currency_selector\"]/div/ul//li"));
System.out.println(list.size());
for (int i=0; i<list.size(); i++){
System.out.println(list.get(i).getText());
}
Output:
3
EUR €
I'm need to get the text from items in dropdown, my code can find all li elements and print number of them, but when I'm trying to print the visible text from them but I'm getting only text from the first option :(
I would be very grateful for a hint...
Part of page source:
<div id="_desktop_currency_selector">
<div class="currency-selector dropdown js-dropdown">
<span>Currency:</span>
<span class="expand-more _gray-darker hidden-sm-down" data-toggle="dropdown">UAH ₴</span>
<a data-target="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="hidden-sm-down">
<i class="material-icons expand-more"></i>
</a>
<ul class="dropdown-menu hidden-sm-down" aria-labelledby="dLabel">
<li >
<a title="European EURO" rel="nofollow" href="http://wasd.com.ua/ru/search?order=product.price.desc&s=dress&SubmitCurrency=1&id_currency=2" class="dropdown-item">EUR €</a>
</li>
<li class="current" >
<a title="Ukrainian UAH" rel="nofollow" href="http://wasd.com.ua/ru/search?order=product.price.desc&s=dress&SubmitCurrency=1&id_currency=1" class="dropdown-item">UAH ₴</a>
</li>
<li >
<a title="Dollar USA" rel="nofollow" href="http://wasd.com.ua/ru/search?order=product.price.desc&s=dress&SubmitCurrency=1&id_currency=3" class="dropdown-item">USD $</a>
</li>
</ul>
<select class="link hidden-md-up">
<option value="http://wasd.com.ua/ru/search?order=product.price.desc&s=dress&SubmitCurrency=1&id_currency=2">EUR €</option>
<option value="http://wasd.com.ua/ru/search?order=product.price.desc&s=dress&SubmitCurrency=1&id_currency=1" selected="selected">UAH ₴</option>
<option value="http://wasd.com.ua/ru/search?order=product.price.desc&s=dress&SubmitCurrency=1&id_currency=3">USD $</option>
</select>
</div>
I've added a tag at the end which seems working.
List<WebElement> list = driver.findElements(By.xpath("//*[#id=\"_desktop_currency_selector\"]/div/ul/li/a"));
Also if you just want to print the text inside <option> tag use this:
List<WebElement> list = driver.findElements(By.xpath("//*[#id=\"_desktop_currency_selector\"]/div/select/option"));
Both of this produce same result.
Output:
3
EUR €
UAH ₴
USD $
// preprare emtpy list
List<String> texts = new ArrayList<String>();
// get the dropdown element
WebElement dropDown = driver.findElement(By.className("link hidden-md-up"));
// get dropdown options
List<WebElement> options = dropDown.findElements(By.tagName("option"));
// collect texts
for (WebElement option: options) {
texts.add(option.getText());
}
This question already has answers here:
'UnexpectedTagNameException' and Element should have been "select" but was "div" error using 'Select' function through Selenium java
(1 answer)
org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "span" while selecting a dropdown value
(2 answers)
Closed 2 years ago.
I'm trying to select an option from a drop-down that has a div tag instead of select. With my below code, I am able to open the respective div, however unable to select the element.
This is the HTML tags:
<div id="selectator_LocationListDD" class="selectator_element single options-hidden" style="width:
100%; min-height: 35px; padding: 6px 12px; flex-grow: 0; position: relative;">
<span class="selectator_textlength" style="position: absolute; visibility: hidden;">
</span>
<div class="selectator_selected_items">
<div class="selectator_selected_item selectator_value_">
<div class="selectator_selected_item_title">--Select--</div>
<div class="selectator_selected_item_subtitle"></div>
</div>
</div>
<input class="selectator_input" placeholder="Search here..." autocomplete="false">
<ul class="selectator_options" style="top: 73px;"><li class="selectator_option selectator_value_">
<div class="selectator_option_title">--Select--</div><div class="selectator_option_subtitle">
</div>
<div class="selectator_option_subtitle2">
</div>
<div class="selectator_option_subtitle3">
</div>
</li>
<li class="selectator_option selectator_value_CST0003970">
<div class="selectator_option_title">21ST STREET</div>
<div class="selectator_option_subtitle">1031 21st</div>
<div class="selectator_option_subtitle2">Lewiston, ID</div>
</li>
<li class="selectator_option selectator_value_CST0003214">
<div class="selectator_option_title">3RD & STEVENS</div>
<div class="selectator_option_subtitle">508 W Third Ave</div>
<div class="selectator_option_subtitle2">Spokane, WA</div>
</li>
<li class="selectator_option selectator_value_CST0003956 active">
<div class="selectator_option_title">9TH AVE</div>
<div class="selectator_option_subtitle">600 S 9th Ave</div>
<div class="selectator_option_subtitle2">Walla Walla, WA</div>
</li>
<li class="selectator_option selectator_value_CST0003991">
<div class="selectator_option_title">10TH & BANNOCK</div>
<div class="selectator_option_subtitle">950 W Bannock St, Ste 100</div>
<div class="selectator_option_subtitle2">Boise, ID</div>
</li>
</ul>
</div>
The Code ni has so far is:
Page Object:
#FindBy(id="selectator_LocationListDD")
WebElement locationDD;
public void select_locationEI(int index) throws InterruptedException {
Thread.sleep(2000);
locationDD.click();
Select locationEI = new Select(locationDD);
locationEI.selectByIndex(index+1);
// wait.until(ExpectedConditions.visibilityOfElementLocated
(By.xpath("//div[#class=\"selectator_selected_item selectator_value_\"]//li["+
(index+1)+"]"))).click();
}
step definition:
#When("user added equipment for each location")
public void user_added_equipment_for_each_location() throws InterruptedException {
atmAgreement = new AgreementsATM(driver);
for(int ei: emptyLocation) {
atmAgreement.click_addNewEquipment_tab();
loaderVisibilityWait();
loaderInvisibilityWait();
atmAgreement.select_locationEI(ei);
atmAgreement.enter_modelText();
String dt = reader.getCellData("ATM", "Depositor Type", 2);
atmAgreement.select_depositorType(dt);
String manufacture = reader.getCellData("ATM", "Manufacturer", 2);
atmAgreement.select_manufacturer(manufacture);
atmAgreement.enter_terminalID();
atmAgreement.click_addButtonEI();
loaderVisibilityWait();
}
emptyLocation.clear();
}
I got an org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "div".
I'm not sure how to handle this as I've only worked with selects before.
Let's say I wanted to select "9TH AVE" for the agent code. How would I go about this?
Any help is appreciated! Thanks.
Use this xpath and get all the option title (findelements).
//ul//li/div[#class='selectator_option_title']
store above element in yourListOFElements
Once you have the list of webelements you can iterate through each entry and compare the innerHTML
yourListOFElements.get(i).getAttribute("innerHTML")
and compare with your required text.
if matches you can click that element
hope you got the idea.
as I see your dropdown list contains search field
<input class="selectator_input" placeholder="Search here..." autocomplete="false">
the best way is to
Select the main div with id="selectator_LocationListDD"
select the search field inside the main div.
type in the search field a unique part of the option name.
then click on the only displayed <li> inside the main div.
that way you avoid using the index, which can change frequently and use the text in the selection which most likely depends on your inserted Test data so you have full control of it.
I am sending defined data from excel file. I tried some code but they are not selecting all the data from excel file at some point of time code is giving me exception for WebElement not found.
Here is the HTML code:
<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
<div id="addDialog" class="hidden ui-dialog-content ui-widget-content" style="display: block; width: auto; min-height: 30px; height: auto; max-height: 351.05px; overflow-y: auto;">
<div class="field-container">
<fieldset class="field-container">
<legend>Contracts:</legend>
<a class="select-all" href="#">Select All</a>
<a class="deselect-all" href="#">Deselect All</a>
<select id="addContract" class="searchable" multiple="multiple" style="position: absolute; left: -9999px;">
<option value="93370956">93370956</option>
<option value="93796167">93796167</option>
<option value="94203239">94203239</option>
</select>
<div id="ms-addContract" class="ms-container">
<div class="ms-selectable">
<input class="search-input" type="text" placeholder="filter" autocomplete="off"/>
<ul class="ms-list" tabindex="-1">
<li id="86355560-selectable" class="ms-elem-selectable">
<span>93370956</span>
</li>
<li id="202890296-selectable" class="ms-elem-selectable">
<span>93796167</span>
</li>
<li id="938848030-selectable" class="ms-elem-selectable">
<span>94203239</span>
</li>
</ul>
</div>
</div>
Need to select values from list.
Efforts done:
This effort for code worked but it selected only one value and then gave exception
WebDriverWait Wait=new WebDriverWait(driver, 10);
Wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//ul[#class='ms-list']/li/span")));
//now you can find element
List<WebElement>options=driver.findElements(By.xpath("//ul[#class='ms-list']/li/span[contains(text(),'"+testData+"')]"));
for (WebElement option: options) {
if(testData.equals(option.getText())) option.click();
}
Tried above code but it only selects one value !!
WebDriverWait Wait = new WebDriverWait(driver, 10);
Wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id='ms-addContract']//descendant::div[#class='ms-selectable']/ul[#class='ms-list']]//span")));
List<WebElement> options = driver.findElements(By.xpath("//*[#id='ms-addContract']//descendant::div[#class='ms-selectable']/ul[#class='ms-list']]//span[contains(text(), '"+testData+"')]"));
for (WebElement option : options) {
if(testData.equals(option.getText()))
option.click();--tried this xpath-no success
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='ms-addContract']/div[1]/input"))).click();
driver.findElement(By.xpath(".//*[#id='ms-addContract']/div[1]/input")).sendKeys(testData);
WebDriverWait wait1 = new WebDriverWait(driver, 10);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='ms-addContract']/div[1]/input"))).sendKeys(Keys.ARROW_DOWN,Keys.ARROW_DOWN,Keys.SPACE);
//Clear the input text value.
driver.findElement(By.xpath(".//*[#id='ms-addContract']/div[1]/input")).clear();---worked but not satisfactory
Please need help to locate the element. I am using keyword driven framework reading values from excel file.
It sounds like you are trying to get all span elements that are contained within a ul element (although correct me if I am wrong). This is the code you are using:
List<WebElement>options = driver.findElements(By.xpath("//ul[#class='ms-list']/li/span[contains(text(),'"+testData+"')]"));
In your case, this XPath will only return 1 value. This is because you are trying to match the contents of each span with an input value "testData". If you want to get all span elements inside of the ul then use:
List<WebElement>options = driver.findElements(By.xpath("//ul[#class='ms-list']/li/span"));
This XPath will select accomplish selecting all span elements in the list. If you need to select only span elements containing text within your testData, then you can iterate over that list selecting the appropriate elements:
ArrayList<WebElement> optionsInTestData = new ArrayList<WebElement>();
for(WebElement element: options){
for(String data: testData){
if(element.getText() == data){
optionsInTestData.add(element);
}
}
}
I dont ask this question lightly, but it proving to be more problematic than I thought. I have trawled through google looking at possible solutions but it seems I just cannot select a specific option from a dropdown list.
If anyone can give me a pointer or a solution it would be very welcome as I am pulling my hair out trying to get this to work.
Here is the html:
<div id="main-content" class="col-xs-12">
<div class="row">
<div
class="form-horizontal col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4">
<div class="col-xs-12">
<h1>Please sign in</h1>
<div class="form-group form-group-sm">
<div class="form-group">
<div class="form-group">
<div class="form-group" data-bind="visible:loginExternal"
style="display: none;">
<div class="form-group">
<span class="k-widget k-dropdown k-header" style="width: 100%;"
unselectable="on" role="listbox" aria-haspopup="true"
aria-expanded="false" tabindex="0" aria-owns=""
aria-disabled="false" aria-readonly="false" aria-busy="false">
<span class="k-dropdown-wrap k-state-default"
unselectable="on"> <span class="k-input"
unselectable="on">Please select ...</span> <span
class="k-select" unselectable="on"> <span
class="k-icon k-i-arrow-s" unselectable="on">select</span>
</span>
</span> <select data-role="dropdownlist" data-text-field="display"
data-option-label="Please select ..."
style="width: 100%; display: none;"
data-value-primitive="true" data-value-field="irn"
data-bind="source: locations, value: selectedLocation">
<option value="822">Alexandra</option>
<option value="800">Ridge</option>
<option value="896">Ture</option>
<option value="899">Grove</option>
<option value="824">Lea</option>
<option value="825">Mount</option>
<option value="894">Cliffe</option>
<option value="788">Bank</option>
<option value="826">Ponga</option>
<option value="259">Post</option>
</select>
</span>
</div>
<div class="form-group">
<span class="k-widget k-dropdown k-header" style="width: 100%;"
unselectable="on" role="listbox" aria-haspopup="true"
aria-expanded="false" aria-owns="loginSubLoc_listbox"
aria-disabled="true" aria-readonly="false" aria-busy="false"
aria-activedescendant="loginSubLoc_option_selected"> <span
class="k-dropdown-wrap k-state-disabled" unselectable="on">
<span class="k-input" unselectable="on"></span> <span
class="k-select" unselectable="on"> <span
class="k-icon k-i-arrow-s" unselectable="on">select</span>
</span>
</span> <select id="loginSubLoc" data-role="dropdownlist"
data-text-field="display"
data-option-label="Please select ..."
style="width: 100%; display: none;"
data-value-primitive="true" data-value-field="irn"
data-bind="source: sublocations, value: selectedsubLocation, enabled: isSublocationEnabled"
disabled="disabled">
<option value="">Please select ...</option>
<option value="0" selected="selected"></option>
</select>
</span>
</div>
<div class="form-group">
<button id="submit" class="btn btn-lg btn-primary btn-block"
type="button" data-bind="click: btnLoginClicked">Login</button>
</div>
I have tried the following:
WebElement element = driver.findElement(By.cssSelector("div>span>select[data-bind='source: locations, value: selectedLocation']"));
Select dropdown = new Select(element);
driver.findElement(By.cssSelector("div.form-group>span>span.k-dropdown-wrap.k-state-default>span.k-input")).click();
dropdown.selectByValue("822");
I get an error: element not visible: Element is not currently visible and may not be manipulated
I also tried the following:
driver.findElement(By.cssSelector(".k-input")).click();
List<WebElement> popupdd = driver.findElements(By.cssSelector("div>span>select[data-bind='source: locations, value: selectedLocation']>option"));
driver.switchTo().activeElement();
int noOptions = popupdd.size();
System.out.println("Total options = " + noOptions);
if (noOptions > 0) {
for (WebElement e : popupdd) {
System.out.println(e.getAttribute("textContent"));
if (e.getAttribute("textContent").contains(location)) {
System.out.println("Trying to click on : " + location);
e.click();
Thread.sleep(500);
break;
} else {
System.out.println("counld find the entry: " + location);
}
}
}
It prints out correctly the option values but cannot click onthe option I want. I get an error: org.openqa.selenium.ElementNotVisibleException: element not visible
Very frustrating. Not sure how to mover forward wit this one.
Any help would be greatly appreciated as I am presently relying on the Robot class to manipulate the dropdown and want to avoid this method.
1st way: it is not the problem to click any element using the same js. As you know how to get any option the last actions remaning is to perform a click. This should work for you:
WebElement hiddenWebElement =driver.findElement(By(..selector of the element....));
((JavascriptExecutor)driver).executeScript("arguments[0].click()",hiddenWebElement);
2nd way:
JavascriptExecutor js = (JavascriptExecutor) driver;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("var x = $(\'#subElement\');");
stringBuilder.append("x.click();");
js.executeScript(stringBuilder.toString());
3rd way: using actions builder, advanced user actions API.
WebElement mnEle;
WebElement sbEle;
mnEle = driver.findElement(By.Id("mnEle")).click();
sbEle = driver.findElement(By.Id("sbEle")).click();
Actions builder = new Actions(driver);
// Move cursor to the Main Menu Element
builder.moveToElement(mnEle).Perform();
// Giving 5 Secs for submenu to be displayed
Thread.sleep(5000L);
// Clicking on the Hidden SubMenu
driver.findElement(By.Id("sbEle")).click();
Hope this will help you :)
Here is the Answer to your Question:
As per your Question, to select the option <option value="822">Alexandra</option> you can consider trying the following piece of code:
WebElement select_dropdownlist = driver.findElement(By.xpath("//*[#data-role='dropdownlist' and #data-text-field='display']"));
Select dropdownlist = new Select(select_dropdownlist);
dropdownlist.selectByVisibleText("Alexandra");
OR
WebElement select_dropdownlist = driver.findElement(By.xpath("//*[#data-role='dropdownlist' and #data-option-label='Please select ...']"));
Select dropdownlist = new Select(select_dropdownlist);
dropdownlist.selectByValue("822");
Let me know if this Answers your Question.
I am having difficulty in clicking a drop down and selecting option from the list. Below screenshot of the application.
Our application uses heavy ExtJS and below is the HTML code for dropdown button and textbox.
<div id="combobox-1115-bodyEl" class="x-form-item-body x-form-trigger-wrap-focus" role="presentation" style="width: 325px;">
<div id="ext-gen1273" class="x-hide-display x-form-data-hidden" role="presentation"></div>
<input id="ext-gen1272" class="x-form-field x-form-text x-form-focus" type="text" autocomplete="off" tabindex="2" size="20" aria-invalid="false" placeholder="Please Select a XXXX..." data-errorqtip="" style="width: 305px; -moz-user-select: text;" role="textbox" aria-describedby="combobox-1115-errorEl" aria-required="true"></input>
<div id="combobox-1115-triggerWrap" class="x-form-trigger-wrap" role="presentation" style="width: 20px;">
<div id="ext-gen1274" class="x-trigger-index-0 x-form-trigger x-form-arrow-trigger x-form-trigger-last x-unselectable" role="button" style="-moz-user-select: none;"></div>
Below is the code for dropdown list options.
<div id="boundlist-1132" class="x-boundlist x-boundlist-floating x-boundlist-default x-layer x-boundlist-above" style="position: absolute; left: 582px; top: 93px; width: 325px; z-index: 19061;" role="listbox" tabindex="-1">
<div id="boundlist-1132-listEl" class="list-ct" style="overflow: auto;">
<ul>
<li id="ext-gen1312" class="x-boundlist-item" role="option">6757</li>
<li id="ext-gen1309" class="x-boundlist-item" role="option">Customer 1</li>
<li id="ext-gen1300" class="x-boundlist-item" role="option">Customer 2</li>
<li id="ext-gen1301" class="x-boundlist-item" role="option">Customer 3</li>
<li id="ext-gen1302" class="x-boundlist-item" role="option">Customer 4</li>
<li id="ext-gen1310" class="x-boundlist-item" role="option">XYZ Company1</li>
</ul>
</div>
Please help me locate the dropdown button and select a list item from it. Thanks in advance!!
Try using explicit wait with more precise selectors.
By css = By.cssSelector("[placeholder='Please Select a Customer...']");
By option = By.xpath("//li[#role='option'][text()='Customer 2']");
WebDriverWait wait = new WebDriverWait(driver, 10);
//Click the dropdown to populate the list
WebElement dropdown = wait.until(ExpectedConditions.presenceOfElementLocated(css));
dropdown.click();
//Click the option. Notice the xpath is using the text of the customer
WebElement value = wait.until(ExpectedConditions.presenceOfElementLocated(xpath));
value.click();
First you have to click dropdown element(mostly with input tag) and then wait for the li webelemnt to appear .. below is the function which expects webelement with ul tag and value.
public void selectValueFromUnorderedList(WebElement unorderedList, final String value) {
List<WebElement> options = unorderedList.findElements(By.tagName("li"));
for (WebElement option : options) {
//System.out.println(option.getText());
if (value.equalsIgnoreCase(option.getText())) {
option.click();
break;
}
}
}