簡體   English   中英

Selenium Webdriver - 我正在嘗試獲取網頁中的所有鏈接

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

這是我使用的代碼,

    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) {

        }
    } 
}

這是我收到的回復,

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**

你能幫忙解決這個問題嗎? 感謝你的幫助!!

它在我的機器上工作。 我沒有使用 geckodriver,因為我的 firefox 版本是 43。錯誤可能是由於 geckodriver。

對於鑄造,不包括開放式支架

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

現在可以用了!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM