如何使用 Selenium 和 Java 从动态下拉列表中 select 自动建议

How to select the auto suggestion from the dynamic dropdown using Selenium and Java

我正在尝试 select Subjects 字段的值,格式如下:https://demoqa.com/automation-practice-form

这是一个输入字段,可根据我们的输入动态给出建议,稍后我们需要从这些建议中 select 值。我无法 select 想要的值。

下面的代码只填充输入区域,但值不是 selected。

driver.findElement(By.id("subjectsInput")).sendKeys("English");
driver.findElement(By.id("subjectsInput")).click(); //This line doesnot click on the desired value.

如何Select想要的值。请帮忙。

要调用唯一的自动建议 英语,您需要诱导 for the elementToBeClickable() and you can use either of the following :

  • cssSelector:

    driver.get("https://demoqa.com/automation-practice-form");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#subjectsInput"))).sendKeys("English");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.subjects-auto-complete__menu"))).click();
    
  • xpath:

    driver.get("https://demoqa.com/automation-practice-form");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='subjectsInput']"))).sendKeys("English");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(@class, 'subjects-auto-complete__menu')]"))).click();
    
  • 浏览器快照:

下面的代码对我有用。

    WebDriver Driver = new ChromeDriver();
    Driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    //Driver.manage().window().maximize();
    String url = "https://demoqa.com/automation-practice-form";
    Driver.get(url);
    WebElement products=Driver.findElement(By.id("subjectsInput"));
    products.sendKeys("English");
    products.sendKeys(Keys.ARROW_DOWN);
    products.sendKeys(Keys.ENTER);