点击硒中自动建议下拉列表中的值

时间:2017-06-12 12:51:19

标签: java selenium

我正在使用java在selenium中开发测试自动化。我的疑问是我使用发送键发送自动建议下拉值    locater.sendKeys("一些值");,
所以在下拉菜单中显示的不止一个建议,当我使用
时 locater.sendKeys(Keys.ARROW_DOWN);
locater.sendKeys(Keys.Enter);
 它始终选择最后一个选项。 如何点击我发送的选项?

2 个答案:

答案 0 :(得分:2)

由于选择为react Select,以下功能将适合您。

在您的情况下,ID为 32

所以你可以称之为

reactSelect("32", "Male"); // reactSelect("32", "male");

功能

public void reactSelect(String id, String... values) {
    By selectDropArrow = By.xpath("//div[@class='Select-control'][span[contains(@id,'react-select-" + id + "')]]/span[@class='Select-arrow-zone']");
    WebElement dropDownArrow = driver.findElement(selectDropArrow);
    dropDownArrow.click();
    if (values != null) {
        for (String value : values) {
            WebElement option = driver.findElement(By.xpath("//div[@id='react-select-" + id + "--list']/div[@class='Select-option' and text()='" + value + "']"));
            option.click();
        }
    }
}

完整示例

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

/**
 *
 * @author Madhanraj
 */
public class SelTest {

    WebDriver driver;

    public SelTest() {
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    public void start() {
        driver.get("http://jedwatson.github.io/react-select/");
        reactSelect("3", "Caramel", "Peppermint");
    }

    public void reactSelect(String id, String... values) {
        By selectDropArrow = By.xpath("//div[@class='Select-control'][span[contains(@id,'react-select-" + id + "')]]/span[@class='Select-arrow-zone']");
        WebElement dropDownArrow = driver.findElement(selectDropArrow);
        dropDownArrow.click();
        if (values != null) {
            for (String value : values) {
                WebElement option = driver.findElement(By.xpath("//div[@id='react-select-" + id + "--list']/div[@class='Select-option' and text()='" + value + "']"));
                option.click();
            }
        }
    }

    public void quit() {
        driver.quit();
    }

    public static void main(String[] args) {
        SelTest ss = new SelTest();
        ss.start();
        ss.quit();
    }

}

答案 1 :(得分:0)

您的代码不应该选择最后一个选项。应选择第一个选项。

如果您想要专门选择您提供的选项,则可以使用下面提到的代码:

    locator.sendKeys("test match");
    Thread.sleep(1000);
    WebElement element_move = driver.findElement(By.xpath("//*[. = 'test match']"));
    Actions actions = new Actions(driver);
    actions.moveToElement(element_move).click().build().perform();
相关问题