【问题标题】:How to select an option from a dropdown through Selenium WebDriver如何通过 Selenium WebDriver 从下拉列表中选择一个选项
【发布时间】:2018-04-11 10:28:55
【问题描述】:

我有以下 Inspected element Id 用于 UI 屏幕中包含几个字段的下拉菜单。

下拉值:

  • 列表项1
  • 列表项2
  • 列表项3

检查的元素 ID:

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

在某些情况下,下拉列表将不包含任何值。

我需要显示一个 sysout 日志,只有当这个下拉列表有至少一个值时。

有人可以建议我如何将其纳入我的 Selenium 测试吗?

目前,我有以下代码来检查服务器是否已启动并测试登录。

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

【问题讨论】:

  • 这个场景中dropDown在哪里使用?
  • 我还没用过。我不知道如何使用它,因为我是 Selenium 的新手。
  • 好的,为此分享相关的 HTML。
  • 能否请您发布完整的下拉html代码
  • 相关HTML?没能得到你。你的意思是我正在测试的整个页面的 HTML?

标签: java selenium selenium-webdriver webdriver selenium-chromedriver


【解决方案1】:

如果下拉菜单由 Select 标记组成,那么您可以使用 Selenium 的 Select 类。

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

如果它是由 Divs 和 spans 组成的,那么你可能想使用这个代码:

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

更新:

HTML 文件:

<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>

使用 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");
        }
    } 

它在我的机器上运行良好。如果您对此有任何疑虑,请告诉我。

注意:
Thread.sleep(3000) 在我的代码中用于可视化目的。

【讨论】:

  • 您可以遵循第一个使用选择类的代码,因为您的 html 代码中包含选择标签和选项标签。
  • WebElement 表示什么?
  • driver.findElement(by.id("some id"));将返回相应的 WebElement。
  • cruise..我关心的是 ID .. 选择 WebElement 的 ID 为“form1:PartialSysAdminKey_adminContractIdField”。当我将其包含在“Select select = new Select(WebElement);”中时你提到,我收到一个错误“没有这样的元素:无法找到元素:{“method”:“id”,“selector”:“form1:PartialSysAdminKey_adminContractIdField”}”。
  • 使用:选择 select = new Select(driver.findElement(by.cssSelector("select[id*="PartialSysAdminKey"]")));并告诉我您是否能够解决您的问题。
【解决方案2】:

根据提到的情况,以下代码可用于检查下拉列表中的元素数量并相应地打印 sysout 日志。在 wait.until 行中,根据下拉菜单中的默认选项,第二个参数“数字”应替换为 0 或 1。即如果下拉列表为空,则使用 0。如果下拉列表的默认选项为“--Select--”,则使用 1。所以基本上你要做的是,等待下拉列表中是否有任何选项,而不是默认内容。您可以根据您的应用程序加载时间更改等待时间。

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

编辑:另一种方式可能是

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

【讨论】:

  • 不起作用 Dheemanth。即使有下拉菜单,也会返回“下拉菜单中没有选项”。
  • 我选择了“1”作为指定“数字”的值。第一个元素。
  • 您是否尝试增加等待时间?该页面可能需要一些时间来加载下拉列表中的选项。可能是新的 WebDriverWait(driver, 30)
  • 是的 .. 也试过了。
  • 我已经编辑了我的答案并添加了另一个可能的解决方案。请尝试并告诉我。
【解决方案3】:

根据您提供的 HTML,您可以使用以下代码块:

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");

【讨论】:

    【解决方案4】:
    <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>
    

    请考虑上面是您的下拉菜单。用于选择月份。我们可以通过三种方式从下拉列表中选择一个选项。

    方法#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
    

    方法#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
    

    方法#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
    

    希望这会有所帮助。

    【讨论】:

      【解决方案5】:
      Select oSelect = new Select(driver.findElement(By.id("PartialSysAdminKey_adminContractIdField")));
      oSelect.selectByValue("List item1");
      

      说明:首先创建一个选择节点元素 thn 的对象,通过该对象调用函数 selectByValue 并传递您的 价值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-13
        • 2023-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多