How to click on All links in web page in Selenium WebDriver

后端 未结 8 2048
余生分开走
余生分开走 2020-12-29 00:04

I have 10 different pages contain different links. How to click on all the links?

Conditions are : i) I don\'t know how many links are there ii) I want to count and

8条回答
  •  Happy的楠姐
    2020-12-29 00:21

    Not sure how efficient it is but I reloaded the links in the same list after each iteration and successfully completed the task.

    String baseURL = "https://www.wikipedia.org/";
    
            driver.get(baseURL);
            List links = driver.findElements(By.xpath("//div[@class='central-featured']/div/a")); 
            System.out.println("The size of the list is: " + links.size());
    
            // Loop through links, click on each link, navigate back, reload the link and
            // continue.
    
            for (int i = 0; i < links.size(); ++i) {
                links.get(i).click();
                driver.navigate().back();
                // reloading the list or there will be stale-element exception
                links = driver.findElements(By.xpath("//div[@class='central-featured']/div/a"));
    
            }
            // print the link text and href values
    
            for (int i = 0; i < links.size(); ++i) {
                System.out.print(links.get(i).getText() + "--> " + links.get(i).getAttribute("href"));
            }
    
            driver.close();
    

提交回复
热议问题