How to get selected option using Selenium WebDriver with Java - java

I want to get the selected label or value of a drop down using Selenium WebDriver and then print it on the console.
I am able to select any value from the drop down, but I am not able to retrieve the selected value and print it:
Select select = new
Select(driver.findElement(By.id("MyDropDown"))).selectByVisibleText(data[11].substring(1 , data[11].length()-1));
WebElement option = select.getFirstSelectedOption();
But all my efforts were in vain. How do I get the selected option?

You should be able to get the text using getText() (for the option element you got using getFirstSelectedOption()):
Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );

Completing the answer:
String selectedOption = new Select(driver.findElement(By.xpath("Type the xpath of the drop-down element"))).getFirstSelectedOption().getText();
Assert.assertEquals("Please select any option...", selectedOption);

In Selenium Python it is:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
def get_selected_value_from_drop_down(self):
try:
select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
return select.first_selected_option.get_attribute("value")
except NoSuchElementException, e:
print "Element not found "
print e

On the following option:
WebElement option = select.getFirstSelectedOption();
option.getText();
If from the method getText() you get a blank, you can get the string from the value of the option using the method getAttribute:
WebElement option = select.getFirstSelectedOption();
option.getAttribute("value");

short answer
Select select = new Select(driver.findElement(By.xpath("//select")));
System.out.println("selected items from the dropdown"+ select.getFirstSelectedOption().getText());

var option = driver.FindElement(By.Id("employmentType"));
var selectElement = new SelectElement(option);
Task.Delay(3000).Wait();
selectElement.SelectByIndex(2);
Console.Read();

Related

How to store value in dropdown using string array? Call in selenium web driver

I am creating script but did not get perfect call. please help me how to create script dropdown value store in array. I an unable to call in selenium web drive.
Dropdown menu scrrenshot: http://prntscr.com/100j0km
Dropdown menu list: http://prntscr.com/100j1og
Thanks
WebElement facultyId = driver.findElement(By.id("faculty_id"));
facultyId.click(); // to make the options to appear
Thread.sleep(500); // if not using implicit wait
List<String> values = new ArrayList<String>();
List<String> texts = new ArrayList<String>();
List<WebElement> options = facultyId.findElements(By.tagName("option"));
for (WebElement option: options) {
values.add(option.getAttribute("value"));
texts.add(option.getText());
}
String[] collectedValues = (String[]) values.toArray();
String[] collectedTexts = (String[]) texts.toArray();
Check Below Answer I have used this script
// options to appear
driver.findElement(By.xpath("//*[#id=\"s2id_autogen3\"]")).click(); // options to appear
Thread.sleep(6000);
driver.findElement(By.xpath("//*[#id=\"s2id_autogen3\"]")).sendKeys("Office Department"); //pass the sendkeys
Thread.sleep(6000);
//Use the Using explicit wait
WebDriverWait Faculties = new WebDriverWait(driver, 120);
WebElement Departments =Faculties.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("*//Put the xpath for finding keyword"))); //Put the xpath for finding keyword
Departments.click(); //Click on finding keyword

how to clear textbox value in selenium webdriver java

and this is my code
WebElement formElement1 = wd.findElement(By.id("updateMasterform"));
List<WebElement> allFormChildElements1 = formElement.findElements(By.xpath("*"));
for (WebElement we : allFormChildElements1) {
System.out.println(we.getAttribute("class"));
}
formElement1.findElement(By.id("editClientName")).clear();
formElement1.findElement(By.id("editClientName")).sendKeys("Mumbai");
Just use type method and enter "" as input:
formElement1.findElement(By.id("editClientName")).sendKeys("")
Sometimes clear doesn't work if the text box have no focus
Try below code to clear a value in text box if clear doesn't work:
formElement1.findElement(By.id("editClientName")).sendkeys(Keys.chord(keys.CONTROL,'a'))
formElement1.findElement(By.id("editClientName")).sendKeys(Keys.DELETE);

Multi select drop down

I am writing code for multi select using selenium(java) where i need the following task to be performed :
select multiple options in drop down
to click on button first selected which will print the first selected option from drop down.
to click on button get all selected which will print the all selected options in order .
I have this code which returns me undefined as a result for 2nd task.
public class MultipleSlectList {
public static WebDriver driver ;
#BeforeTest
public void startbrowser () throws Exception {
System.out.println("launching browser");
System.setProperty("webdriver.gecko.driver", "H:\\Selenium3\\geckodriver-v0.19.1-win32\\geckodriver.exe");
driver = new FirefoxDriver();
driver.get("http://www.seleniumeasy.com/test/basic-select-dropdown-demo.html");
}
#Test
public void selectlist () throws Exception {
WebElement ele1 = driver.findElement(By.id("multi-select"));
Select se= new Select(ele1);
se.selectByValue("New Jersey");
Thread.sleep(2000);
se.selectByValue("Texas");
Thread.sleep(2000);
se.selectByValue("Florida");
Thread.sleep(2000);
//Thread.sleep(10000);
WebElement btn1= driver.findElement(By.id("printMe"));
btn1.click(); // it is supposed to return New Jersy
WebElement firstOption = se.getFirstSelectedOption();
System.out.println("The First selected option is::" +firstOption.getText());
List <WebElement> oSize = se.getAllSelectedOptions();
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 = oSize.get(i).getText();
// Printing the stored value
System.out.println(sValue);
}
}
}
Please help me to proceed further.
I have tried with jquery as well but no luck .The result is same as "undefined" in both case .
Thanks !
Steps to select all dropdown options:
Find the SELECT WebElement by webdriver.
Create Select class which is used to operate dropdown list.
Get all options list in the dropdown list.
Loop the options list, get each option value and use
Select.selectByValue(optionValue) to select it.
Then all the dropdown option has been selected.
Below article has the code example to implement above scenario.
http://www.dev2qa.com/select-dropdown-list-selenium-webdriver/

Selenium cannot select dropdown on span element

To get the element I have used a nested loop.I am able to click on dropdwn.PFB the code:
List<WebElement> webElements1 = driver.findElements(By.className("selectboxit"));
for(WebElement webElement1 : webElements1) {
if( webElement1.getAttribute("name").equals("TransactionHistoryFG.OUTFORMAT"))
{
WebElement web1 = webElement1.findElement(By.className("selectboxit-text"));
web1.click();
}
}
When i am trying to use Select on webelement i am getting error :
org.openqa.selenium.support.ui.UnexpectedTagNameException: Element
should have been "select" but was "span"
How can i select dropdown i span element?
Possible solution for selecting dropdown using selenium webdriver is:
Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down")));
select.deselectAll();
select.selectByVisibleText("Value1");
Instead of the approach you mentioned above, let me know if this helps :)
List<WebElement> webElements1 = driver.findElements(By.cssSelect(".selectboxit"));
for(WebElement webElement1 : webElements1) {
if( webElement1.getAttribute("name").equals("TransactionHistoryFG.OUTFORMAT"))
{
WebElement web1 = webElement1.findElement(By.className("selectboxit-text"));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", web1);
}
}
Well, it is not the best way to do it, but in some cases it can be used:
it will open your combobox
driver.findElements(By.cssSelect(".selectboxit")).click()
now, you just need to write the specified value
driver.findElements(By.cssSelect(".selectboxit")).sendKeys("<value>");
OR
driver.findElements(By.cssSelect(".selectboxit")).sendKeys(Keys.ARROW_DOWN).
Use "ARROW_DOWN" as wanted to select your specified value.

creating gmail account using selenium

Not able to Select the month for Date of Birth.
Code I am using is:
driver.findElement(By.xpath(".//*[#id = 'BirthMonth']/div")).click();
Thread.sleep(3000);
WebElement months = driver.findElement(By.xpath(".//[#id='BirthMonth']/div[2]/div[#id=':1']"));
Thread.sleep(2000);
months.click();
I also tried with by using DropDownList case. But Not able to set any Month.
Please Say me the Solution.
You can use keyboard event replace mouse.
WebElement birthMonth = driver.findElement(By.id("BirthMonth"));
birthMonth.click();
Actions action = new Actions(driver);
action.sendKeys(Keys.DOWN).sendKeys(Keys.ENTER).perform();
We can use sendKeys directly:
driver.findElement(By.xpath(".//*[#id='BirthMonth']/div[1]")).sendKeys("July");
You can wrap this up in a function
public void selectBirthMonth(int monthIndex)
{
driver.findElement(By.cssSelector("#BirthMonth > div")).click();
driver.findElements(By.cssSelector("#BirthMonth > div.goog-menu > div.goog-menuitem")).get(monthIndex - 1).click();
}
and then call it like
selectBirthMonth(9); // 1 = January
WebElement month = wd.findElement(By.xpath("//[#id=\"BirthMonth\"]/div[1]"));
month.click();
Thread.sleep(3000);
//wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//fetch months from the dropdown and store it in a list
List<WebElement> month_dropdown = wd.findElements(By.xpath("//[#id=\"BirthMonth\"]/div[2]/div/div"));
//iterate the list and get the expected month
for (WebElement month_ele:month_dropdown){
String expected_month = month_ele.getAttribute("innerHTML");
// Break the loop if match found
if(expected_month.equalsIgnoreCase("August")){
month_ele.click();
break;
}
}
It is not drop down value , you have to click on drop down arrows and then click on any value which you have to pass from script.
Code is below:
System.setProperty("webdriver.chrome.driver", "E:/software and tools/chromedriver_win32/chromedriver.exe");
WebDriver driver= new ChromeDriver();
//FirefoxDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://accounts.google.com/SignUp");
Thread.sleep(5000);
driver.findElement(By.xpath(".//*[#id='BirthMonth']/div[1]/div[2]")).click();
driver.findElement(By.xpath(".//*[#id=':7']/div")).click();
it is workable code for Birthmonth
Please find below link for same type of Question
Not able to select the value from drop down list by using Select method in Selenium

Categories

Resources