java - 使用按键解决自动提示下拉方法的任何方法

标签 java selenium selenium-webdriver selenium-chromedriver selenium-ide

语言:java

我一直在尝试自动化自动提示下拉菜单,但如果我在单行中给出文本和键,则不会为网站提供加载选项。记住这一点,我继续使用线程 sleep 方法并等待建议加载,但光标从 Web 元素中出来,并且未执行按键操作。请帮我解决这个问题......

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class suggestivedropdown {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        System.setProperty("webdriver.chrome.driver","C:\\Users\\teddy\\Downloads\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.makemytrip.com/");
    //  driver.findElement(By.xpath("//input[@id='fromCity']")).clear(); this is if it contains default option
      WebElement source=driver.findElement(By.xpath("//input[@id='fromCity']"));
      source.sendKeys("HYD");
    Thread.sleep(3000);
    source.sendKeys(Keys.ARROW_DOWN);
    source.sendKeys(Keys.ENTER);
      WebElement destination=driver.findElement(By.xpath("//input[@id='toCity']"));
       destination.sendKeys("MUM");
       Thread.sleep(3000);
       destination.sendKeys(Keys.ARROW_DOWN);
       destination.sendKeys(Keys.ENTER);

最佳答案

您不应在代码中使用硬编码 sleep 。如果您遇到同步问题,请使用等待来避免问题,请参阅以下解决方案:

    driver.get("https://www.makemytrip.com/");
    WebDriverWait wait = new WebDriverWait(driver, 30);

    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='fromCity']"))).sendKeys("Hyd");
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//p[contains(text(),'Hyderabad, India')]"))).click();

    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='toCity']"))).sendKeys("Mumbai");
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//p[contains(text(),'Mumbai, India')]"))).click();

关于java - 使用按键解决自动提示下拉方法的任何方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61125654/

相关文章:

java - Maven 生成原型(prototype)获取包变量作为目录格式

java - 无法找到按钮并使用点击功能 : Selenium WebDriver with Java

java - 如何将Windows上Eclipse编写的JSP转换为Linux?

java - 将选定的 Jtable 行添加到列表模型

python - 如何使用 Selenium Webdriver 从多个页面获取信息?

python - 抓取隐藏元素

node.js - 如何多次点击同一个元素而不嵌套? (Selenium-Webdriver + NodeJS + Mocha)

javascript - 无法测试是否在 Protractor 中选中了复选框

java - 什么是 setElementConverter 以及它在 Selenium WebDriver 中如何工作?

java - 如何为 JConsole 的密码文件加密密码