我有一个列表,每个部分下都有多个链接。每个部分都有不同的墨水,我需要单击每个部分下的特定链接。我已经写了下面的代码,但是当它执行时,它会告诉我: stale element reference: element is not attached 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();
}
}
发布于 2019-03-21 17:44:25
您可以使用:
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();
}
});
}
希望这对你来说足够清楚了。
https://stackoverflow.com/questions/55277007
复制相似问题