【问题标题】:Autocomplete selenium自动完成硒
【发布时间】:2019-08-12 02:32:24
【问题描述】:

我的列表在每个部分下都有多个链接。每个部分都有不同的墨水我需要单击每个部分下的特定链接。我已经编写了下面的代码,但是当它执行时它给了我:stale element reference: element is not attach to the page document。

driver.findElement(By.xpath("//*[@id=\"s2id_CountryId\"]/a")).click();
List<WebElement> link2 = driver.findElements(By.xpath("//*[@id=\"select2-drop\"]/ul//li[.]"));

for (int i = 0; i <= link2.size(); i++) {
    if (link2.get(i).getText().equalsIgnoreCase("ALGERIA")) {
        link2.get(i).click();
    }
}

driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[@id=\\\"s2id_GlobalId\\\"]/a")).click();
List<WebElement> link = driver.findElements(By.xpath("//*[@id=\"select2-drop\"]/ul//li[.]"));

for (int i = 0; i <= link.size(); i++) {
    if (link.get(i).getText().equalsIgnoreCase("BNZ (Global)")) {
        link.get(i).click();
    }
}

【问题讨论】:

  • 哪一行会抛出该错误?另外,在您的问题中发布相关的 HTML。

标签: java selenium selenium-webdriver autocomplete


【解决方案1】:

你可以使用:

 List<WebElement> listOfLinks = driver.findElements(By.xpath("yourXpath"));
 listOfLinks.forEach(link -> {
     if (link.getText().equalsIgnoreCase("your text")) {
         link.click();
         }
     });

forEach 将从您的列表中获取每个链接,并且它将处理您在这些括号之间的任何内容。在这种情况下,if 条件。

对于第二部分,您也可以使用 foreach。您也可以为每个链接设置等待,这样每个链接都会等待一段时间。

如果你想使用 lambdas,你需要 java 8。

编辑:在你得到我的信息之后,我已经设法为你写了这个:

public static void main(String[] args) throws InterruptedException {
    System.setProperty("webdriver.chrome.driver",".//src//browser//chromedriver.exe");
    yourMethodName("xpathExample", "xPathListPathExample", "iWantToFindThis","theTextIWantToComplete");
}

private static void yourMethodName(String xPathOfTheElement,String xPathListPath, String theTextYouWantToFind, String theTextYouWantToComplete) throws InterruptedException {
    driver.findElement(By.xpath(xPathOfTheElement)).sendKeys(theTextYouWantToComplete);
    Thread.sleep(2000);

    List<WebElement> listOfLinks = driver.findElements(By.xpath(xPathListPath));
    listOfLinks.forEach(link -> {
        if (link.getText().equalsIgnoreCase(theTextYouWantToFind)) {
            link.click();
        }
    });
}

希望这对你来说已经足够清楚了。

【讨论】:

  • 感谢您的回复......我还需要知道一件事......我如何在运行时调用它......同时我必须在同一页面上处理另外两个自动完成字段
  • 这里我已经附上了代码..请概述一下,..并给我建议以进行更改..
猜你喜欢
  • 2017-05-06
  • 2010-10-14
  • 2017-10-27
  • 2015-08-20
  • 2012-06-12
  • 2013-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多