2015-12-12 59 views
0

這是中國的網站正常工作。(LinkJsoup不指定網站

我想用Jsoup解析這個網站,但似乎Jsoup不工作。

一個非常簡單的代碼:

Document doc = Jsoup.connect("http://pchome.megatime.com.tw/stock/sid1101.html") 
      .timeout(0).get(); 
Elements links = doc.select("a"); 

for(Element e : links) { 
    System.out.println(e.text()); 
} 

並沒有什麼出來。

我的Jsoup可以解析每一個網站,除了這一個。任何人都可以幫我解決這個問題嗎?

+0

非常感謝。有用。 –

+0

我想問一個問題:指定用戶代理的目的是什麼?無論使用哪個網址,用戶代理都需要添加嗎?感謝您的回覆。 –

回答

2

網站正在做一件有趣的事情,首先它會返回一個重定向(http代碼302),然後返回一個用is_check=1參數進行表單提交的迷你頁面。我們必須遵循所有這些步驟。

此外,您需要指定用戶代理。

總結,只是做:

Response res = Jsoup.connect("http://pchome.megatime.com.tw/stock/sid1101.html") 
     .followRedirects(false) 
     .timeout(0) 
     .method(Method.GET) 
     .header("User-Agent", "Mozilla/5.0") 
     .execute(); 

String location = res.header("Location"); 

res = Jsoup.connect("http://pchome.megatime.com.tw/stock/sid1101.html") 
     .timeout(0) 
     .data("is_check", "1") 
     .method(Method.POST) 
     .header("User-Agent", "Mozilla/5.0") 
     .header("Referer", location) 
     .execute(); 

Document doc = res.parse(); 
Elements links = doc.select("a"); 

for(Element e : links) { 
    System.out.println(e.text()); 
} 

,你會得到大量的鏈接。