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

China☆狼群 提交于 2021-02-10 13:03:32

问题


I am trying to select the value for Subjects field in the following form: https://demoqa.com/automation-practice-form

It is an input field that dynamically gives suggestions based on our input and later we need to select values from those suggestions. I am unable to select the desired value.

The Below code only populates the input area but the value is not selected.

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

How to Select the desired value. Please help.


回答1:


To invoke click on the only auto suggestion English you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

  • 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();
    
  • Browser Snapshot:

toolsqa_subject




回答2:


The code below worked for me.

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


来源:https://stackoverflow.com/questions/63301508/how-to-select-the-auto-suggestion-from-the-dynamic-dropdown-using-selenium-and-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!