Issues in value selection from dropdown in Selenium webdriver - selenium

I am trying to select the value from the drop down. Below is the HTML of that dropdown on the login screen.
<div class="form-group">
<label for="j_companyname">Company</label>
<select id="j_companyname" name="companyname" size="1" onclick="onAccountLostFocus();" style="cursor: pointer;"><option value="AUTO_DEPLOYER">AUTO_DEPLOYER</option><option value="ES188CLIENT1">ES188CLIENT1</option><option value="ES188CLIENT10">ES188CLIENT10</option><option value="ES188CLIENT11">ES188CLIENT11</option><option value="ES188CLIENT12">ES188CLIENT12</option><option value="ES188CLIENT13">ES188CLIENT13</option><option value="ES188CLIENT14">ES188CLIENT14</option><option value="ES188CLIENT15">ES188CLIENT15</option><option value="ES188CLIENT16">ES188CLIENT16</option><option value="ES188CLIENT17">ES188CLIENT17</option><option value="ES188CLIENT18">ES188CLIENT18</option><option value="ES188CLIENT19">ES188CLIENT19</option><option value="Primatics">Primatics</option></select>
<img src="ui/img/ajax-loader.gif" style="margin: 3px; position: absolute; display: none;">
"
I tried to locate element via different locators but unable to pick any value. My script is:
if( driver.findElement(By.id("j_companyname")).isEnabled()){
System.out.println("Element is Enable");
WebElement select = driver.findElement(By.id("j_companyname"));
List<WebElement> options = select.findElements(By.tagName("option"));
for (WebElement option : options)
{
if("ES188CLIENT16".equals(option.getText()))
// option.click();
option.submit();
}
}
else{
System.out.println("Element is Disabled");
}
Please help.

Pleas look below code
Select drpCountry = new Select(driver.findElement(By.id("j_companyname")));
drpCountry.selectByVisibleText("ES188CLIENT16");
// these also can help you
//drpCountry.selectByIndex("givenindex");
//drpCountry.selectByValue("ES188CLIENT16");

As you are trying to select the value from the drop down, lets assume we have to select AUTO_DEPLOYER from the dropdown. To select AUTO_DEPLOYER from the dropdown you can use the following code block :
WebElement my_select = driver.findElement(By.id("j_companyname"));
Select select = new Select(my_select);
new WebDriverWait(driver, 5).until(ExpectedConditions.elementToBeSelected(By.xpath("//select[#id='j_companyname']//option[contains(.,'AUTO_DEPLOYER')]")));
select.selectByVisibleText("AUTO_DEPLOYER");

Related

How to select specific element form list by using Selenium WebDriver?

Can anyone guide me how to select specific element from list view
from using below code.
<div id="menu" class="tabalign k-widget k-reset k-header k-menu k-menu-horizontal" data-role="menu" tabindex="0" role="menubar" aria-activedescendant="menu_mn_active">
<li class="k-item k-state-default k-first mainMenu2" role="menuitem" id="menu_mn_active"><span class="k-link"><img class="k-image" alt="" src="/Images/Common/Module_2.png"><span id="2">Profiles</span></span></li>
<li class="k-item k-state-default mainMenu3" role="menuitem"><span class="k-link"><img class="k-image" alt="" src="/Images/Common/Module_3.png"><span id="3">Contacts</span></span></li>
And I have tried below code but it is not worked for me:
WebElement element = driver.findElements(By.xpath("//*[#id=\"menu_mn_active\"]"));
element.click();
Try this code in Java (it selects first element from dropdown):
driver.findElement(By. id("menu")).click();
List<WebElement> options = driver.findElements(By. cssSelector(".k-item.k-state-default"));
for (WebElement opt : options) {
if (opt.getText().equals("Profiles")) {
opt.click();
}
}
You can use like this:
First get location of all elements:
List<WebElement> element = driver.findElements(By.xpath("//*[#id=\"menu_mn_active\"]"));
For the first element:
element.get(0).click(); // for first element
For the second element:
element.get(1).click(); // for second element

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

Alternative ways for selecting value from drop down list in selenium using java

I have got an error with select the value from drop down list in selenium using java.
//Select the Warehouse
Select Warehouse= new Select(driver.findElement(By.xpath(Xpath.warehouse_SVR)));
System.out.println("Element is identified ");
Warehouse.selectByValue("3");
System.out.println("Value is selected");
Thread.sleep(1000);
js.executeScript("window.scrollTo(0,0)");
I used the methods which are related to select the value from drop down list. Here I mentioned the .selectByValue() method. Even though I used .selectByIndex() or .selectByVisibleText() methods, still I have got the error. What is the possible way to select the value from drop down list?
This is the Html code for that particular drop down list.
<select id="ctl00_cphbody_rptRNDViewer_ctl04_ctl05_ddValue" class="aspNetDisabled" style="font-family: Verdana; font-size: 8pt; width: 217px;" onchange="javascript:setTimeout('__doPostBack(\'ctl00$cphbody$rptRNDViewer$ctl04$ctl05$ddValue\',\'\')', 0)" name="ctl00$cphbody$rptRNDViewer$ctl04$ctl05$ddValue">
<option value="1">- All -</option>
<option value="2">Damage Warehouse-1000003061</option>
<option value="3" selected="selected">Primary Warehouse-1000003061</option>
<option value="4">VAN</option>
</select>
Check out following
Use implcit wait before, Warehouse.selectByValue("3");
Try following updated code :
Select Warehouse= new Select(driver.findElement(By.xpath(Xpath.warehouse_SVR)));
System.out.println("Element is identified ");
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(presenceOfElementLocated(Warehouse));
Warehouse.selectByValue("3");
System.out.println("Value is selected");
Thread.sleep(1000);
js.executeScript("window.scrollTo(0,0)");
Hope it will help you.
public boolean selectValueFromDropDown(String searchValue) {
WebElement element = driver.findElement(By.Id("ctl00_cphbody_rptRNDViewer_ctl04_ctl05_ddValue"));
element.click();
element.sendKeys(searchValue);
element.sendKeys(Keys.ENTER);
return true;
}

Drop Down value in selenium using java

Could you please help me in selecting drop down value in selenium using java code.
My issue is that in HTML code, i do not have SELECT class.
This is the code i have tried :
List<WebElement> elements = driver.findElement(By.id("Some Value"));
for (WebElement element: elements){
new Actions(driver).sendKeys(Keys.Arrow_Down).perform();
if(Element.getText().equals("Cliam Document")){
element.click();
}
}
Below is html snippet :
<input class="dijitReset dijitInputInner" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" aria-autocomplete="both" aria-required="true" tabindex="0" id="ecm_widget_AddContentItemGeneralPane_0_entryTemplateSele‌​‌​ctor" value="" aria-invalid="true" type="text">
<span class="dijitPlaceHolder dijitInputField">Enter or select an entry template</span>
<input name="ecm_widget_AddContentItemGeneralPane_0_entryTemplateSe‌​‌​lector" value="" type="hidden"></div>
you can try following code (Here I'm assuming that dropdown options appear after clicking the dropdown field):
WebElement yourDropdown = driver.findElement(By.cssSelector("#ecm_widget_AddContentItemGeneralPane_0_entryTemplateSele‌​‌​ctor"));
yourDropdown .click();
List<WebElement> elements = driver.findElements(By.cssSelector("#ecm_widget_AddContentItemGeneralPane_0_entryTemplateSele‌​‌​ctor input"));
for (WebElement element: elements){
if(Element.getText().equals("Cliam Document")){
element.click();
}
}
Follow these steps:
Step 1: Enter value in the input field.
driver.findElement(By.xpath("Enter xpath here")).sendkeys("enter text here");
Step 2: Now to select value from the list
List<WebElement> elements = driver.findElements(By.xpath("Some Value"));
for (WebElement element: elements){
String element_text = element.gettext();
if(element_text.equals("Cliam Document")){
element.click();
}
}
Follow Below steps, will be able to select value from dropDown
Step 1.
WebElement dropdownTab = driver.findElements(By.xpath("dropdown locator")).click(); //Click on the dropdown tab
Step2:
List options = driver.findElements(By.tag_name('option')); //Get all the options
Step 3:
for (WebElement element: options){
if(options.getText().equals("Text Name which needs to be selected")){
element.click();
break;
}
}
This should work, if still you are facing issue - Please provide the url where you are trying...will post the exact code

element not visible: Element is not currently visible and may not be manipulated - Selenium webdriver

Following is the html
<div id="form1:customertype" class="ui-selectonemenu ui-widget ui-state-default ui-corner-all ui-state-hover" style="width: 165px;">
<div class="ui-helper-hidden-accessible">
<select id="form1:customertype_input" name="form1:customertype_input" tabindex="-1">
<option value="S">Staff</option>
<option value="C">Customer</option>
<option value="N">New To Bank</option></select></div>
<div class="ui-helper-hidden-accessible"><input id="form1:customertype_focus" name="form1:customertype_focus" type="text" readonly="readonly"></div>
<label id="form1:customertype_label" class="ui-selectonemenu-label ui-inputfield ui-corner-all" style="width: 149px;">Staff</label>
<div class="ui-selectonemenu-trigger ui-state-default ui-corner-right ui-state-hover"><span class="ui-icon ui-icon-triangle-1-s ui-c"></span></div></div>
The stylesheet of class="ui-helper-hidden-accessible" is
ui-helper-hidden-accessible {
border: 0;
clip: rect(0 0 0 0);
height: 0px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 0px;
}
Following is my code
WebElement customerType = driver.findElement(By.id("form1:customertype_input"));
Select select = new Select(customerType);
select.selectByVisibleText("New To Bank");
When I try to select "New to Bank" from the dropdown I get exception
element not visible: Element is not currently visible and may not be manipulated - Selenium webdriver
I have tried WebDriverWait technique but of no use, any ideas ?
I don't believe the text for that option is actually visible before you attempt to select it. Try selecting by value instead.
WebElement customerType = driver.findElement(By.id("form1:customertype_input"));
Select select = new Select(customerType);
select.selectByValue("N");
You may need to actually click the selector before being able to select an option, though.
WebElement customerType = driver.findElement(By.id("form1:customertype_input"));
new WebDriverWait(driver, 15).until(
ExpectedConditions.elementToBeClickable(customerType));
customerType.click();
Select select = new Select(customerType);
select.selectByValue("N");
try performing click on customerType before you create object of Select
Well, I found a work around to solve my problem but I am not happy with this. anyways what I did is focused on the div element that controls the dropdown by clicking it and and then sending down arrows keys twice followed by enter key. This selects my desired option. I used the following method
driver.switchTo().activeElement()
I also had the same problem and after hours I realized the browser was trying to click in a element before the page load.
So I create a sleep to solved the problem:
sleep(1)
P.S. - This is a solution that I really don't like.
I'm just pointing you the reason for that.
The best you can do is to check the page that you have the problem and try to optimize the load time.
I encounter the same problem. I have tried many methods.
Finally, the following python code solved the error.
I use javascript code to make the element visible before selecting the option.
css = 'select#state' # css selector of the element
js = """const data_options = Array.from(document.querySelectorAll('{css}'));
data_options.forEach(a=>{{a.style='display:block;';}});""".format(css=css)
self.driver.execute_script(js)
Maybe it's helpful for you!