以前就有在寫抓網頁的程式,我用過Visual Stdio,也用過Java內建的來抓,不過效果還好,日前看到有人用這隻cURL,感覺還蠻不錯的。
要去模擬瀏覽器操作,例如使用者登入、Session、Cookie、掛Proxy等,都可以輕易辦到,若有要做抓網頁回來剖析的程式的話,可以考慮一下。
cURL官網 - http://curl.haxx.se
cURL使用手冊 - http://curl.haxx.se/docs/manpage.html
以下大概備忘一下常用的指令:
--url 指定要抓取的網址
-A 指定Agent名稱
-b 指定使用Cookie檔案
-c 指定建立Cookie檔案
-d 指定POST的資料
-L 自動重新導向
-s 不顯示處理的訊息
-o 指定輸出檔案
大概寫一下簡單小程式在Java執行,當然的你也要先下載cURL(for Windows),醬才能執行阿!
public static void main(String[] args) {
String result = "";
String[] cmd = { "curl.exe", "-L", "-A", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)", "-c", "cookie.txt", "-b", "cookie.txt", "--url", "http://www.google.com.tw" };
try {
Process proc = Runtime.getRuntime().exec(cmd);
int ptr = 0;
StringBuffer buffer = new StringBuffer();
while ((ptr = proc.getInputStream().read()) != -1) {
buffer.append((char) ptr);
}
result = buffer.toString();
proc.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(result);
}