简体   繁体   中英

Selenium Webdriver - I'm trying to get all links in a Webpage

Here is the code that I used,

    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.sql.Driver;
    import java.util.List;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;

    public class VerifyLinks {

    //@SuppressWarnings("deprecation")
    public static void main(String[] args) throws InterruptedException 
    {
        System.setProperty("webdriver.gecko.driver",
            "C:\\Users\\sselvaraj\\Documents\\Java\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.get("https://www.google.com/#q=selenium");
        List<WebElement> links = driver.findElements(By.tagName("a"));
        System.out.println("Total links are "+links.size());
        for(int i=0;i<links.size();i++)
        {
            WebElement ele= links.get(i);
            String url=ele.getAttribute("href");
            verifyLinkActive(url);
        }
    }
    public static void verifyLinkActive(String linkUrl)
    {
        try 
        {
            URL url = new URL(linkUrl);
            HttpURLConnection httpURLConnect=HttpURLConnection)                
            url.openConnection();
            httpURLConnect.setConnectTimeout(3000);
            httpURLConnect.connect();
            if(httpURLConnect.getResponseCode()==200)
            {
                System.out.println(linkUrl + " - "+httpURLConnect.getResponseMessage());
            }
            if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)  
            {
                System.out.println(linkUrl + " - "
                    +httpURLConnect.getResponseMessage() + " - "  
                    +HttpURLConnection.HTTP_NOT_FOUND);
            }
        } catch (Exception e) {

        }
    } 
}

Here is the response that I received,

Sep 20, 2016 10:19:13 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
1474384754549   Marionette  INFO    Listening on port 53039
Sep 20, 2016 10:19:18 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
**Total links are 0**

Can you please help to resolve this issue. Appreciate your help!!

It's working on my machine. I am not using geckodriver as my firefox version is 43. error might be due to geckodriver.

For casting, an Open bracket is not included

HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();

It works now!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM