user3166813
user3166813

Reputation: 99

Open every link in loop (Selenium)

I just cracked my head trying to find how make it work. I am trying to force Selenium open link by link, but it opens on first link again and again, console output shows that loop is working correctly. Tried to use while loop but it doesn`t work too. I am trying to open link after link and change number of the li element to open further link.

for (int footer_links = 1; footer_links < 6; footer_links++) {
    WebElement self_service_bi = driver.findElement(By.xpath("//div/div/ul/li['$footer_links']/a"));
    self_service_bi.click();
    File srcFile1 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    File targetFile1 = new File("D:\\DataPineScreenshots\\" + driver.getTitle() + ".png");
    FileUtils.copyFile(srcFile1, targetFile1);
    driver.navigate().back();
    System.out.print(footer_links + "\n");
}

Upvotes: 0

Views: 1052

Answers (2)

Piotr Boho
Piotr Boho

Reputation: 2778

fix your syntax

By.xpath("//div/div/ul/li['$footer_links']/a")

by

By.xpath("//div/div/ul/li[" + footer_links + "]/a")

Upvotes: 1

Vivek Singh
Vivek Singh

Reputation: 3649

driver.findElement will always return the first element of the type. Use driver.findElements function to get list of all matching the given xpath. But dont do that in loop cause everytime it will open the same link. Try out like:

List<String> lstUrls = new ArrayList<String>();
List<WebElement> lstEle = driver.findElements(By.xpath("//div/div/ul/li['$footer_links']/a"));
for (WebElement element : lstEle)
    lstUrls.add(element.getAttribute("href"));

for (String string : lstUrls) {
    driver.get(string)
    File srcFile1 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    File targetFile1 = new File("D:\\DataPineScreenshots\\" +  driver.getTitle() + ".png");
    FileUtils.copyFile(srcFile1, targetFile1);
    driver.navigate().back();
    System.out.print(footer_links + "\n");
}

Upvotes: 0

Related Questions