【问题标题】:How to automate autocomplete textbox如何自动化自动完成文本框
【发布时间】:2023-03-26 00:06:01
【问题描述】:

我正在尝试自动化一个测试用例,其中文本框提供智能以自动完成该字段。 请在下面找到自动完成文本框的链接: 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();

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

【问题讨论】:

    标签: java selenium autocomplete ui-automation


    【解决方案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(); 不是一个好习惯

    希望对你有所帮助。

    【讨论】:

    • 我试过了,但我的声誉是 11,它说我的声誉不足以这样做。对不起那个 amol
    【解决方案2】:

    因为您使用的动态 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();
                }
         }
    
    
    }
    

    【讨论】:

    • 感谢您的帮助。它的工作。我稍微更改了代码。 ` List option = dr.findElements(By.className("ui-menu-item")); for(WebElement x : option) { if(x.getText().toLowerCase().equals("java")) { x.click(); } }`
    猜你喜欢
    • 2011-04-18
    • 2010-09-22
    • 2020-05-17
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多