如何自动完成自动填充文本框

时间:2017-12-27 22:04:28

标签: java selenium autocomplete ui-automation

我正在尝试自动化一个测试用例,其中文本框提供智能以自动完成该字段。 请在下面找到自动填充文本框的链接: http://demoqa.com/autocomplete/

请找到我写的代码

  dr.findElement(By.id("tagss")).sendKeys("a");
  Thread.sleep(300);
//  dr.findElement(By.id("ui-id-53")).click();
  Actions act = new Actions(dr);
  act.moveToElement(dr.findElement(By.id("ui-id-53"))).click().build().perform();

此代码无法在浏览器提供的智能中查找和查找选项。请帮忙。

2 个答案:

答案 0 :(得分:1)

您无法在DOM中找到自动建议的选项元素,因为这些选项的HTML ID会在页面重新加载后发生更改。

在这种情况下,您需要使用XPath来标识元素。假设您要单击Java自动建议选项,那么您的代码应该是 -

System.setProperty("webdriver.chrome.driver","C:\\WebDriver\\TestAutomation\\grid\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://demoqa.com/autocomplete/");
driver.manage().window().maximize();
driver.findElement(By.id("tagss")).sendKeys("a");
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("ui-id-1"))));
WebElement javaOption = driver.findElement(By.xpath(".//li[@class='ui-menu-item' and text()='Java']"));
javaOption.click();

使用Thread.sleep();

是不好的做法

希望这对你有所帮助。

答案 1 :(得分:0)

因为您正在使用可能在运行时更改的动态ID。 试试这个代码,让我知道任何疑问 -

public class AutoSuggest {

     public static void main(String[] args) throws InterruptedException {
            try {

                  System.setProperty("webdriver.chrome.driver", "C:\\Users\\Ranosys\\workspace\\MyTest\\chromedriver.exe");
                  WebDriver driver = new ChromeDriver();
                  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                  WebDriverWait wait=new WebDriverWait(driver,50 );

                  driver.manage().window().maximize();

                  driver.get("http://demoqa.com/autocomplete/");
                  driver.findElement(By.id("tagss")).sendKeys("a");
                  Actions act = new Actions(driver);
                  List<WebElement> lst= driver.findElements(By.xpath("//li[contains(@id,'ui-id')]"));
                  for(WebElement element:lst){
                      element.click();
                      break;
                  }

            } catch (Exception e) {
                e.printStackTrace();
            }
     }


}