java - 自动完成文本框第一个选项选择

标签 java selenium xpath css-selectors webdriverwait

我想选择自动完成文本框中显示的第一个选项。下面是我尝试过但没有得到所需输出的代码。

代码:

public void clickSublink() throws IOException, InterruptedException {   
    System.setProperty("webdriver.chrome.driver","F:\\Amitha\\chromedriver.exe");
    WebDriver dr=new ChromeDriver();
    dr.get("http://demoqa.com/autocomplete/");
    dr.findElement(By.xpath("//input[@id='tags']")).sendKeys("b");
    dr.findElement(By.xpath("//ul[@id='ui-id-1']//child::li")).click();
}

最佳答案

中选择第一个选项文本框,您需要使用 elementToBeClickable() 并且可以使用以下任一 Locator Strategies :

  • css选择器:

    driver.get("http://demoqa.com/autocomplete/");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.ui-autocomplete-input#tags"))).sendKeys("b");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("ul.ui-autocomplete>li>div"))).click();
    
  • xpath:

    driver.get("http://demoqa.com/autocomplete/");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='ui-autocomplete-input' and @id='tags']"))).sendKeys("b");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[@class='ui-menu ui-widget ui-widget-content ui-autocomplete ui-front']/li/div"))).click();
    

关于java - 自动完成文本框第一个选项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59835308/

相关文章:

java - Spring 安全。不同角色对同一页面的不同 View ,可能吗?

python - 是否可以在不使用 jenkins 上的 "PyAutoGUI"库的情况下使用键盘操作?

php - 在 Selenium Chrome 中将语言设置为 en-UK 以进行 Behat 测试

xml - 如何使用 XPath 选择多个可能的文本值?

python-3.x - 获取段落标签中的所有文本

java - 通过矩阵变换在 Canvas 上绘制位图是否会影响位图?

java - 位置分隔文本解析的设计模式?

java - 如何遍历 iFrame 中的不同框架?

java - WebElements 列表中的 Selenium Web Driver Stale Reference 异常

java - XPath 2.0 中的函数 Reverse() : how can use it to evaluate an expression?