Selenium - 使用 Java 单击下拉列表并选择一个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31250125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:20:20  来源:igfitidea点击:

Selenium - Using Java to click on a dropdown list and select a value

javaseleniumhtml.dropdownlistfor

提问by Nyhan

I am trying to automate the download of a large set of indicators on a continuous basis. So far with the script I can open the URL, login, switch tab, and go to the desired section. I am having an issue clicking on a dropdown and selecting a value to extend the list from 10 to 100.

我正在尝试自动连续下载大量指标。到目前为止,我可以使用脚本打开 URL、登录、切换选项卡并转到所需的部分。我在单击下拉列表并选择一个值以将列表从 10 扩展到 100 时遇到问题。

Here is my code thus far

到目前为止,这是我的代码

SoltraDownload.java

SoltraDownload.java

import java.util.Scanner;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class SoltraDownload {

public static void main(String[] args) {

    //PROMPT USER FOR Password
    //System.out.print("Please Enter Your Username: ");
    //Scanner scanner = new Scanner(System.in);
    //String username = scanner.next();

    //PROMPT USER FOR Username
    //System.out.print("Please Enter Your Password: ");
    //String password = scanner.next();

    //GET WEB DRIVER
    System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("EDITED FOR QUESTION");
    driver.manage().window().maximize();    

    //GET INSTANCE OF Soltra HOME PAGE
    SoltraHomePage SoltraHomePage = new SoltraHomePage(driver);

    //LOGIN TO SOLTRA
    SoltraHomePage.loginP("EDITED FOR QUESTION");
    SoltraHomePage.loginU("EDITED FOR QUESTION");
    SoltraHomePage.loginC();

    //MOVE TO FEEDS PAGE
    SoltraHomePage.FeedPage();

    //PAGE CLICK ON FEED SELECTION
    SoltraHomePage.ChooseFeed();

    //SELECT DROPDOWN value 100
    SoltraHomePage.Dropdown();
}

}

SoltraHomePage.java

SoltraHomePage.java

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;


public class SoltraHomePage {

@FindBy(how = How.ID, using = "username") private WebElement Username;
@FindBy(how = How.ID, using = "password") private WebElement Password;
@FindBy(how = How.ID, using = "loginbutton") private WebElement loginbutton;
@FindBy(how = How.LINK_TEXT, using = "Feeds") private WebElement Feeds;
@FindBy(how = How.ID, using = "feedlist") private WebElement feedlist;
@FindBy(how = How.CLASS_NAME, using = "container") private WebElement container;
@FindBy(how = How.LINK_TEXT, using = "Default") private WebElement Default;
@FindBy(how = How.CSS, using = "control-bar") private String control;

// Create a new instance of a driver
WebDriver driver = new HtmlUnitDriver();

public SoltraHomePage(WebDriver driver) {
    PageFactory.initElements(driver, this);
}

public void loginU(String text) {
    this.Username.clear();
    this.Username.sendKeys(text);
}

public void loginP(String text) {
    this.Password.clear();
    this.Password.sendKeys(text);
}

public void loginC(){
    this.loginbutton.click();
}

public void FeedPage() {
    this.Feeds.click();
}

public void ChooseFeed() {
    feedlist.findElement(By.partialLinkText("Default")).click();
}

public void Dropdown() {
    //Code to select dropdown value
}
}

Here is a subset of the html code - I am looking to choose the value 100 in the dropdown

这是 html 代码的一个子集 - 我希望在下拉列表中选择值 100

<div class="row control-bar">

<div class="col-sm-4"></div>

<div class="col-sm-4">

<ul class="pager">

<li class="previous"><input type="button" class="btn btn-default" data-    bind="click: goFirst, disable: page()==1" value="&lt;&lt;"></li>

<li class="previous"><input type="button" class="btn btn-default" data-  bind="click: goPrev, disable: page()==1" value="&lt;"></li>

<li><small data-bind="text: page"></small> of <small data-bind="text: totalPages"></small> (<small data-bind="text: totalRows"></small>

<small data-bind="if: totalRows()!==1">rows</small><small data-bind="if: totalRows()==1">row</small>)</small></li>

<li class="next"><button class="btn btn-default" data-bind="click: goNext, disable: page() == totalPages()">&gt;</button></li>

<li class="next"><button class="btn btn-default" data-bind="click: goLast, disable: page() == totalPages()">&gt;&gt;</button></li>

</ul>
</div>
    <div class="col-sm-4">
    <ul class="pager">
        <li class="pull-right"><small>Indicators per page: </small>
            <select data-bind="value: pageSize, event: { change: loadData }" style="width:auto">
                <option value="5">5</option>
                <option value="10">10</option>
                <option value="20">20</option>
                <option value="50">50</option>
                **<option value="100">100</option>** //This is the value I am looking to choose
        </select>
    </li>
</ul>

回答by NaviSaysListen

I always create a custom actions class and place these in there:

我总是创建一个自定义操作类并将它们放在那里:

public static void selectByValue(WebElement element, String value) {
    Select selectElement = new Select(element);
    selectElement.selectByValue(value);
}
public static void selectByText(WebElement element, String text) {
    Select selectElement = new Select(element);
    selectElement.selectByVisibleText(text);
}

These take your WebElement, convert it to a Select element (org.openqa.selenium.support.ui.Select), and use Select methods to select your option. This only works with html select elements. You would use it like so:

这些获取您的 WebElement,将其转换为 Select 元素 (org.openqa.selenium.support.ui.Select),然后使用 Select 方法来选择您的选项。这仅适用于 html select 元素。你会像这样使用它:

At the top:

在顶部:

@FindBy(how = How.CSS, using = "li.pull-right select") private WebElement soltraSelect;

In a test:

在测试中:

CustomActions.selectByValue(soltraSelect, "100");

回答by nemelianov

You can do it with Select object or define a correct XPath:

您可以使用 Select 对象或定义正确的 XPath:

1) Using Select:

1) 使用选择:

Select element = new Select(webelement);
element.selectByValue(value);

2) Using XPath:

2) 使用 XPath:

By option = By.xpath("//select[@class = 'expression']/option[@value = 'value']");
driver.findElement(option).click();

回答by Saifur

Since the value attribute has the same value as text I would suggest to go for the following cssSelector for better search result

由于 value 属性与文本具有相同的值,我建议使用以下 cssSelector 以获得更好的搜索结果

String val = "100";
By css = By.cssSelector("select>option[value='" + val + "']");
driver.findElement(css).click();

On the other hand, you can use selectByValuemethod to accomplish the same thing instead to visual text. See the doc

另一方面,您可以使用selectByValue方法来完成相同的事情,而不是可视化文本。查看文档