自动完成硒

问题描述 投票:0回答:1

我有一个列表,每个部分下面有多个链接。每个部分都有不同的墨水,我需要点击每个部分下的特定链接。我编写了下面的代码但是当它执行时它给了我:陈旧元素引用:元素没有附加到页面文档。

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();
    }
}
java selenium selenium-webdriver autocomplete
1个回答
0
投票

您可以使用:

 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();
        }
    });
}

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

© www.soinside.com 2019 - 2024. All rights reserved.