I use cssselector with Keys class. But the value is not selected
browser.findElement(By.cssSelector("input[id='loadingPort']")).sendKeys("Odes", Keys.DOWN, Keys.ENTER);
I want to select the value Odessa from drop down list:
I'm not sure how the website is populating that dropdown, but maybe you could enter your text and then select the first option like this:
browser.findElement(By.cssSelector("input[id='loadingPort']")).sendKeys("Odes");
browser.findElement(By.cssSelector("input[id='loadingPort']")).findElements(By.tagName("option")).get(0).click()
/** OR */
browser.findElement(By.cssSelector("input[id='loadingPort']:first-child")).click()
Sorry, I'm not familiar with java or cssSelectors... just Selenium. If you can clean up that code, that should work if the website is dynamically adding options to the dom.
One more using xpath:
browser.findElement(By.xpath("input[#id='loadingPort']/option[1]")).click()
There are multiple ways to handle dropdown value
- dropdown.selectByVisibleText("Text");
- dropdown.selectByIndex(2); (Index starts with zero always in list)
- dropdown.selectByValue(“Text”)
Sample Code:
Select oSelect = new Select(driver.findElement(By.cssSelector("input[id='loadingPort']")));
// Select option (Odessa(UKR))
oSelect.selectByVisibleText("Odessa(UKR)"); // Using sleep command so that changes can be noticed
Thread.sleep(2000);
// : Select option 'using Index
oSelect.selectByIndex(1);
Thread.sleep(2000);
// Print all the options for the selected drop down and select one option of your choice
// Get the size of the Select element
List<WebElement> oSize = oSelect.getOptions();
int iListSize = oSize.size();
// Setting up the loop to print all the options
for(int i =0; i < iListSize ; i++){
// Storing the value of the option
String sValue = oSelect.getOptions().get(i).getText();
// Printing the stored value
System.out.println(sValue);
// Putting a check on each option that if any of the option is equal to 'Africa" then select it
if(sValue.equals("Odessa(UKR)")){
oSelect.selectByIndex(i);
break;
}
}
Related
Scenario:
I have a WebTable where i go and enter the Search Criteria and based on the Search Criteria the Matching records appears. Then i Need to select 2 checkbox from the table .
My Question is - The Code has the option to select checkbox but i need to select any Two checkbox and Second after selecting the checkbox i need to come out of the Loop..And there could be 2 or more rows in the WebTable
Below is my Code:
List chekcboxoptions = driver.findElements(By.xpath("//label[contains(#class,'mat-checkbox-layout')]")); List DemandSelection = driver.findElements(By.xpath("//tbody[#role='rowgroup']//tr//td[contains(#class,'mat-column-demandId')]"));
for(WebElement demandselection:DemandSelection)
{
Random random = new Random();
int index = random.nextInt(chekcboxoptions.size());
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(0, 100)");
chekcboxoptions.get(index).click(); = If i
insert a break after selecting one checkbox it comes out of the loop but i need to select two checkbox .
HTML OF THE Web Table:
Continue Back searchfilter_alt More Filters Demand ID Cargo OD / BU Load Port Discharge Port Laycan Start Date Laycan End Date GBPO Dead Line 4378SELTESTTECHMTESSINGAPOREHONGKONG2030-04-092040-06-152055-12-30 4379SELTESTTECHMTESSINGAPOREHONGKONG2030-04-092040-06-152055-12-30 4380SELTESTTECHMTESSINGAPOREHONGKONG2030-04-092040-06-152055-12-30 4381SELTESTTECHMTESSINGAPOREHONGKONG2030-04-092040-06-152055-12-30
Here, you should not iterate all the elements, just generate 2 random number and click the select option.
int randOne = random.nextInt(chekcboxoptions.size());
chekcboxoptions.get(randOne).click();
int randTwo = random.nextInt(chekcboxoptions.size());
chekcboxoptions.get(randTwo).click();
Do not use for loop for this
I am trying to select an option from a drop down. If there is no drop down options are visible then script execution should continue.
Please find my code below -
List<WebElement> drop_down_options = driver.findElements(By.className("mat-option"));
if (drop_down_options.size() == 0) {
System.out.println("drop down options are not visible");
} else {
drop_down_options.get(0).click();
}
Here It is taking long time to execute the script if there are no drop down option is present. In my web page some of the drop downs are disabled (which has default value) so I don't want to click or select the option.
But it stuck for some times(more than 4 minutes) in the first line of the code which I mentioned above.
Even if there are element is not visible it waits for some time,so that my script takes time to execute.
I have tried by
isDisplayed(), isEnabled() ,isPresent
try catch
Please give me a solution to continue my script if there are no elements visible in the page
Updated comment:
I have tried all the solutions as mentioned below
1.In first option Select select = new Select( drop_down_options); shows me error saying that "cast argument drop_down_options to WebElement"
2.where as in the second option getText() returns place holder value and other help text message near the input field
GetAttribute() returns null
tried with below code but same result which takes time to exceute if there are no options
for (int d = 0; d < dropdowns.size(); d++) {
Thread.sleep(1000);
System.out.println("----------------" +dropdowns.get(d).getAttribute("value"));
System.out.println("----------------" +dropdowns.get(d).getText());
dropdowns.get(d).click();
Thread.sleep(1000);
WebDriverWait wait=new WebDriverWait(driver,10);
wait.until(ExpectedConditions.visibilityOfAllElements(drop_down_options));
try{
if (drop_down_options.size()==0) {
drop_down_options.get(0).click();
}
}catch(Exception e)
{
e.printStackTrace();
}
If your DOM is using options tag for drop down then try below :
List<WebElement> drop_down_options = driver.findElements(By.className("mat-option"));// Assuming class name is from parent tag.
Select select = new Select(drop_down_options);
List<WebElement> allOptions = select.getOptions();
option 2
try to get default value of dropdown using gettext() or getattribute()
you can check attribute value is =="DISABLE" don't click.
Or you can get default value and check if it is not null then only perform click action
Option 3
try and catch {} it should work if not working put your work and details. Juts a note Catch should not have return statements to continue after your exception.
here is my html:
The solution was simple, i put a select object and get thougth the method getAllOptions but it doesn't work and know i'm doing this to get not the id (value) i want the option's text:
WebElement optionElement = driver.findElement(By.xpath("//select[#id=\"" + selectToFind + "\"]/option["+ randomItemIndex + "]"));
optionSelected = optionElement.getText();
being selectToFind the select's id which is FORM_FIELD_EndUser_planning and randomItemIndex which comes from a method that returns a random value taking in account the size of options in the list:
List <WebElement> itemsInDropdown = driver.findElements(By.xpath("//select[#id=\""+ selectToFind + "\"]/option"));
All tries of the object optionElement (like .getText()) returns "" and i'm stuck with this.
I think you can use
option.getAttribute("innerText");
or
option.getAttribute("innerHTML");
Or expand your Select element (by click) and then try to get a text of options because .getText() method returns only visible text
I want to automate drop down menu using Selenium web driver using Java, but the HTML page has <option disabledselected>----</option> (Ref to attached screenshot)
I want to select 2nd menu item from drop down. I've tried many things but every time I'm get an error message.
1st Approach - using ByVisibleText:
public void selectHomeCommunity(String name){
Select hmecomm= new Select(hmecommdropdown);
hmecomm.selectByVisibleText(name);
}
public <Webelement> SelfRegistrationPage Community(String pass) {
// TODO Auto-generated method stub
enterPassKey(pass);
System.out.println("Entered into Community method");
pressGoBtn();
}
2nd Approach - JavascriptExecutor:
((JavascriptExecutor)driver).executeScript("document.getElementById('hmecommdropdown').options.item(0).click().;");
3rd Approach - getFirstSelectedOption:
String selectedLabel = new Select(driver.findElement(By.id("CommunityDropdown"))).getFirstSelectedOption().getText();
Every time I'm getting same error as:
waiting for visibility of [[ChromeDriver: chrome on XP
(9a6751455dba60b65479430ff8f9aa00)] -> id: CommunityDropdown]
If the dropdowns are from a language such as angular then using Select may not work. My suggestion is us seleniums click operations.
Click the dropdown to open it
Use driver.findElements to find all the webelements for the options inside the dropdown
Iterate through the elements and pull out the text in the elements. When you find the text you are expecting perform the click
Something like the following may be useful:
public void clickDropdownOption(WebDriver driver, String option) throws Exception{
waitForDropdownMenuToBeVisible(driver);
WebElement dropdownMenu = driver.findElement(dropdownMenuLocator);
List<WebElement> optionElements = dropdownMenu.findElements(dropdownOptionLocator);
for(int i=0; i < optionElements.size(); i++){
if(optionElements.get(i).getText().equals(option)){
click(driver, optionElements.get(i));
waitForDropdownMenuToBeinvisible(driver);
return;
}
}
throw new Exception("Dropdown option " + option + " was not found");
}
Obviously if it is a normal HTML dropdown then use the conventional approach
In my app I have two <select> tags. The first one changes the options inside the second one and enables it in the onchange event.
When I use the Select object provided by Selenium2 it doesn't fire that event when running in IE8 (works great in FF and when I do it manually).
Select select = new Select(getElementByName(name));
element.selectByValue(value);
The first <select> changes as expected. However, the second <select> remains empty and disabled. I tried this as a workaround:
if(ie) {
WebElement select = getElementByName(name);
WebElement option = select.findElement(By.cssSelector("[value='"+value+"']"));
List<WebElement> options = select.findElements(By.cssSelector("option"));
//select the first element
options.get(0).click();
//make sure the select is focused
select.click(); //open
select.click(); //close
Keyboard keyboard = getWebDriver().getKeyboard();
for(int i = 0; i < options.size() && option.getAttribute("selected") == null; i++) {
keyboard.pressKey(Keys.DOWN);
//note: if i do a Thread.sleep(100); here, it works more consistently, but still not 100%
}
} else {
// Do the above snippet
}
but now I get inconsistent results. The desired <option> always gets selected, while only sometimes does the event get fired.
Obviously the best option is getting the Select to work in IE8. Has anyone else seen this issue? Seems like a bug in Selenium2. Is there a known workaround for this?
After talking with some of the Selenium folk in the #selenium IRC chat room I settled on this fix:
WebElement selectElement = getElementByName(name);
Select select = new Select(selectElement);
element.selectByValue(value);
if(usingIE) {
webDriver.executeScript("$(arguments[0]).fireEvent('change');", selectElement);
}
Am using below code to select a value in 'Country' list (once 'Country' value is selected, corresponding 'State' list is loading):
WebElement selectCountry = driver.findElement(By.id("country"));
List<WebElement> options = selectCountry.findElements(By.tagName("option"));
for(WebElement option : options){
if(option.getText().equalsIgnoreCase("India")){
option.click();
break;
}
}
Note - This select operation takes much more time IE when compare to FF. You may need to increase command timeout time using driver.manage().
It looks like you are already implementing the SelectElement class so have you tried this
WebElement element = getElementByName(name);
element.FindElement(By.CssSelector("option[value='" + value + "']").Select();