0

I have the following Inspected element Id for a dropdown with a few fields in a UI screen.

DropDown values:

  • List item1
  • List item2
  • List item3

Inspected Element ID:

<select id="form1:PartialSysAdminKey_adminContractIdField" name="form1:PartialSysAdminKey_adminContractIdField" class="selectOneMenu" size="1">

There will be cases when the drop down will hold no values.

I need to display a sysout log, only when this drop down has atleast one value.

Can someone please suggest how can I incorporate this in my Selenium testing?

Currently, I have this following code that checks whether the server is up and tests a login.

package testPackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class TestClass {

    public static void main(String[] args) {

        ChromeOptions options = new ChromeOptions();
        options.addArguments("headless");

        System.setProperty("webdriver.chrome.driver", "D:\\Softwares\\chromedriver_win32\\chromedriver.exe");

        WebDriver driver = new ChromeDriver();
        driver.get("https://bigdata/steward.jsp");

        if (driver.getTitle().equalsIgnoreCase("Login")) {
                serverStatus = "UP";
        } else {
            serverStatus = "DOWN";
        }
        System.out.println("Server is " + serverStatus + ".");

        if (serverStatus.equalsIgnoreCase("UP")) {
            driver.findElement(By.id("username")).sendKeys("username");
            driver.findElement(By.id("password")).sendKeys("password");
            driver.findElement(By.id("login")).click();

            String newUrl = driver.getCurrentUrl();

            if (newUrl.equalsIgnoreCase("https://bigdata/error.jsp")) {
                System.out.println("Incorrect username/password.");
            } else {
                System.out.println("Logged in successfully.");
            }
        } else {
            System.out.println("Login could not be done.");
        }
        driver.quit();
    }
}
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Mike
  • 721
  • 1
  • 17
  • 44

5 Answers5

3

If a Drop Down is made of Select tag then you can use Select class of Selenium.

Select select = new Select(WebElement);
select.selectByIndex(int index);
select.selectByValue(String value);
select.selectByVisibleText(String text);  

If it is made of Divs and spans then you might wanna use this code :

List<WebElement> options = driver.findElements(by.xpath(" your locator"));
for(WebElement element : options){
 if(element.getText().equals(" your value from drop down")){
    element.click();
}
}

Update :

HTML File :

<html>
<head>
<title>StackOverFlow Problems </title>
</head>
<body>
<select id="form1:PartialSysAdminKey_adminContractIdField" name="form1:PartialSysAdminKey_adminContractIdField" class="selectOneMenu" size="1"> 
<option value=" "></option> 
<option value="Lstitem1">List item1</option> 
<option value="Lstitem2">List item2</option> 
<option value="Lstitem3">List item3</option> 
</select
</body>
</html>

Automation code using Java + Selenium :

public class Mike {

    static WebDriver driver;
    static WebDriverWait wait;

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "D:\\Automation\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, 20);
        driver.get("file:///C:/Users/HunteR/Desktop/Automation/abc.html");
        Thread.sleep(3000);
        Select select = new Select(driver.findElement(By.cssSelector("select[id*='adminContractIdField']")));
        select.selectByValue("Lstitem3");
        }
    } 

It is working mightily fine on my machine. Please let me know if you have any concerns related to this.

Note :
Thread.sleep(3000) was used in my code for visualization purpose.

cruisepandey
  • 28,520
  • 6
  • 20
  • 38
  • You can follow first code that is using select class, since your html code contains select tag and option tags inside it. – cruisepandey Apr 11 '18 at 11:34
  • What does the WebElement denote? – Mike Apr 11 '18 at 11:52
  • driver.findElement(by.id("some id")); will return the respective WebElement. – cruisepandey Apr 11 '18 at 11:54
  • cruise..my concern is the ID .. the select WebElement has the ID "form1:PartialSysAdminKey_adminContractIdField".. When I include that in the "Select select = new Select(WebElement);" you mentioned, I get an error "no such element: Unable to locate element: {"method":"id","selector":"form1:PartialSysAdminKey_adminContractIdField"}". – Mike Apr 11 '18 at 12:16
  • use : Select select = new Select(driver.findElement(by.cssSelector("select[id*="PartialSysAdminKey"]"))); and update me whether you are able to resolve your problem. – cruisepandey Apr 11 '18 at 12:34
  • Nope ! Syntax error on token "PartialSysAdminKey_adminContractIdField", invalid AssignmentOperator – Mike Apr 11 '18 at 12:47
  • Okay I will make a HTML with provided code and if it works, I will update you ! – cruisepandey Apr 11 '18 at 15:23
  • I've created a HTML file and put the code provided by you. Please find my updated answer. – cruisepandey Apr 11 '18 at 17:02
  • Thanks Cruise. I'm exactly appending your same code with my code. But still I get this error, Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"select[id*='adminContractIdField']"} ! Will there be any other issues in any of my setting/configuartion? – Mike Apr 12 '18 at 04:28
  • Mike, We get NoSuchElementExceptions, when our webdriver is not able to find the WebElement present in DOM. Could you check ,when we are using this locator : select[id*='adminContractIdField'] , how many elements are present in DOM ? That'd be help for diagnosing this issue. – cruisepandey Apr 12 '18 at 06:00
1

As per the case mentioned, following code can be used to check the number of elements in the dropdown and print sysout log accordingly. In the wait.until line, the 2nd argument 'number' should be replaced with either 0 or 1 according to the default options present in the dropdown. i.e If dropdown is empty use 0. If the dropdown has a default option as '--Select--', then use 1. So basically what you will be doing is, waiting if there is any option in the dropdown, more than the default content. You can change the wait time according to your application load time.

try {new WebDriverWait(driver, 15).until(ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath("//select[@id='form1:PartialSysAdminKey_adminContractIdField']/option"), number));
            System.out.println("Drop down has at least one value present");
        } catch (Exception e) {
            System.out.println("No options in the drop down");
        }

Edit : Another way could be

List<WebElement> list_Items=driver.findElements(By.xpath("//select[@id='form1:PartialSysAdminKey_adminContractIdField']/option"));
        if(list_Items.size()>1){
            System.out.println("Drop down has at least one value present");
        }
        else{
            System.out.println("No options in the drop down");
        }
1

As per the HTML you have provided you can use the following code block :

WebElement elem = driver.findElement(By.xpath("//select[@class='selectOneMenu' and contains(@id,'PartialSysAdminKey_adminContractIdField')]"));
Select mySelect = new Select(elem);
//selecting the first item by index
mySelect.selectByIndex(1);
//selecting the second item by value
mySelect.selectByValue("Lstitem2");
//selecting the third item by text
mySelect.selectByVisibleText("List item1");
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
1
<select id="ddMonth" name="ddMonth" style="color:#000;margin:0;min-width:65px;" onchange="Setoptvariable()" class="reqCheck">
              <option value="">MM</option>
              <option value="01">Jan</option>
              <option value="02">Feb</option>
              <option value="03">Mar</option>
              <option value="04">Apr</option>
              <option value="05">May</option>
              <option value="06">Jun</option>
              <option value="07">Jul</option>
              <option value="08">Aug</option>
              <option value="09">Sep</option>
              <option value="10">Oct</option>
              <option value="11">Nov</option>
              <option value="12">Dec</option>
 </select>

Consider above is your drop down. It is for selecting a month. We can select an option from the drop-down in three ways.

Method #1:

new Select(driver.findElement(By.id("ddMonth"))).selectByIndex(0); // This will select 'MM' option in the dropdown
new Select(driver.findElement(By.id("ddMonth"))).selectByIndex(1); // This will select 'Jan' option in the dropdown
new Select(driver.findElement(By.id("ddMonth"))).selectByIndex(2); // This will select 'Feb' option in the dropdown

Method #2:

new Select(driver.findElement(By.id("ddMonth"))).selectByValue(); // This will select 'MM' option in the dropdown
new Select(driver.findElement(By.id("ddMonth"))).selectByValue("01"); // This will select 'Jan' option in the dropdown
new Select(driver.findElement(By.id("ddMonth"))).selectByValue("02"); // This will select 'Feb' option in the dropdown

Method #3:

new Select(driver.findElement(By.id("ddMonth"))).selectByVisibleText("MM"); // This will select 'MM' option in the dropdown
new Select(driver.findElement(By.id("ddMonth"))).selectByVisibleText("Jan"); // This will select 'Jan' option in the dropdown
new Select(driver.findElement(By.id("ddMonth"))).selectByVisibleText("Feb"); // This will select 'Feb' option in the dropdown

Hope this will help.

0
Select oSelect = new Select(driver.findElement(By.id("PartialSysAdminKey_adminContractIdField")));
oSelect.selectByValue("List item1");

Explanation : first create an object of select node element thn , By that object call function selectByValue and pass your value.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352