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

后端 未结 8 2073
余生分开走
余生分开走 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条回答
  •  渐次进展
    2020-12-29 00:23

    You can use 2 logics to handle

    1. Get the link and hit it in your browser and validate
    2. Get the link and use REST Web service to validate link.

    Using REST WS would be the easiest way to validate links.

    Below code works fine for me.

    public class Testing{
    
        public static void main(String[] args) {
            try{
                WebDriver driver = new FirefoxDriver();
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                driver.manage().window().maximize();
                driver.navigate().to("https://www.amazon.in/");
                List links = driver.findElements(By.tagName("a"));
                System.out.println("Number of links : " + links.size());
                for(WebElement e : links) {
                    String linkText = e.getAttribute("href");
                    System.out.println("Link -->>" +linkText);
                    if(linkText!=null && !linkText.isEmpty()) {
                        HttpPost post = new HttpPost(linkText);
                        HttpClient client = HttpClientBuilder.create().build();
                        HttpResponse res = client.execute(post);
                        String s = res.getStatusLine().toString();
                        if(s.equals("HTTP/1.1 200 OK")) {
                            System.out.println("Navigated");
                            //your code to handle logic 
                        } else {
                            //your code to handle logic with other response code
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println(e.getStackTrace());
            }
        }    
    }
    

提交回复
热议问题