如何使用 Selenium 和 Java 从非 select 下拉菜单中单击并 select 一个选项

How to click and select an option from a non select dropdown using Selenium and Java

我开始使用 Selenium 实现自动化,这是我第一次独自完成它,我在这里找不到下拉列表的正确代码 https://demoqa.com/automation-practice-form 最后有一个“州和城市列表”。对于州,您必须单击“Select州”,然后它会为您提供选项,因此您必须单击所需的选项。

这是我的代码,我尝试了不同的选项,但这是最接近正确运行代码的选项(但它仍然没有做它需要做的事情) 我知道它不能用 Select 完成,因为它是 div,我只能使用:

driver.findElement()

代码试验:

//Select state and city
driver.findElement(By.id("state")).click();     
driver.findElement(By.xpath("//body/div/div/div/div/div/div/form/div[10]/div[2]/div[1]/div[1]/div[1]/div[1]")).click();

图片A: enter image description here

图 B:

图 C: enter image description here

is a non element. To select an item from the State dropdown you need to induce for the elementToBeClickable() and you can use the following :

driver.get("https://demoqa.com/automation-practice-form");
((JavascriptExecutor)driver).executeScript("return arguments[0].scrollIntoView(true);", new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div#state div[class$='placeholder']"))));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div#state div[class$='placeholder']"))).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(., 'Uttar Pradesh')]"))).click();

参考资料

您可以在以下位置找到一些相关的详细讨论:

感谢那些花时间帮助我的人.. 我找到了解决方案!也许还有另一种方法,但这是我发现的方法,自从我第一次编写代码以来,我真的很高兴。 我所做的是逐步进行,直到找到“输入”,所以我使用 sendKeys。(keys.Enter);因为它不适用于 .click();

后来我意识到只有...................................... ......................... state.sendKeys("NCR") ...
state.sendKeys(Keys.ENTER);

也可以正常工作...所以...代码非常简单..

public void selectStateandCity (){ WebDriverWait wait = new WebDriverWait(driver, 20);

    wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//div[contains(text(),'Select State')]"))));
    wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.cssSelector("#state > div"))));
    driver.findElement(By.xpath("//div[@id='state']//div[@class='css-1g6gooi']"));
    driver.findElement(By.xpath("//body/div[@id='app']/div/div/div/div/div/form[@id='userForm']/div[@id='stateCity-wrapper']/div/div[@id='state']/div/div/div/div[1]"));
    state.sendKeys("NCR");
    state.sendKeys(Keys.ENTER);
    
    driver.findElement(By.xpath("//div[contains(text(),'Select City')]"));
    driver.findElement(By.xpath("//body//div[@id='app']//div[@id='city']//div//div//div[2]"));
    driver.findElement(By.xpath("//body/div[@id='app']/div/div/div/div/div/form[@id='userForm']/div[@id='stateCity-wrapper']/div/div[@id='city']/div/div/div/div[1]"));
    city.sendKeys("Delhi");
    city.sendKeys(Keys.ENTER);
driver.get("https://demoqa.com/automation-practice-form");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.id("react-select-3-input")))).sendKeys("NCR");