2016-09-20 218 views
1

這裏是我使用的代碼,硒的webdriver - 我試圖讓所有鏈接在網頁中

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

能否請您有助於解決這個問題。感謝你的幫助!!

+0

該代碼沒有編譯(行'HttpURLConnection httpURLConnect = HttpURLConnection)') – kotoj

回答

0

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

相關問題