java爬取百度首頁源代碼
阿新 • • 發佈:2017-06-20
clas read 意思 出現異常 nts java.net new 有意思 all
爬蟲感覺挺有意思的,寫一個最簡單的抓取百度首頁html代碼的程序。雖然簡單了一點,後期會加深的。
1 package test; 2 3 import java.io.BufferedReader; 4 import java.io.InputStreamReader; 5 import java.net.URL; 6 import java.net.URLConnection; 7 8 public class Main 9 { 10 public static void main(String[] args)11 { 12 // 定義即將訪問的鏈接 13 String url = "https://www.baidu.com/"; 14 // 定義一個字符串用來存儲網頁內容 15 String result = ""; 16 // 定義一個緩沖字符輸入流 17 BufferedReader in = null; 18 try 19 { 20 // 將string轉成url對象 21 URL realUrl = newURL(url); 22 // 初始化一個鏈接到那個url的連接 23 URLConnection connection = realUrl.openConnection(); 24 // 開始實際的連接 25 connection.connect(); 26 // 初始化 BufferedReader輸入流來讀取URL的響應 27 in = new BufferedReader(new InputStreamReader(connection.getInputStream()));28 // 用來臨時存儲抓取到的每一行的數據 29 String line; 30 while ((line = in.readLine()) != null) 31 { 32 // 遍歷抓取到的每一行並將其存儲到result裏面 33 result += line + "\n"; 34 } 35 } catch (Exception e) 36 { 37 System.out.println("發送GET請求出現異常!" + e); 38 e.printStackTrace(); 39 } // 使用finally來關閉輸入流 40 finally 41 { 42 try 43 { 44 if (in != null) 45 { 46 in.close(); 47 } 48 } catch (Exception e2) 49 { 50 e2.printStackTrace(); 51 } 52 } 53 System.out.println(result); 54 } 55 } 56
java爬取百度首頁源代碼