標籤:一個 異常 儲存 rgs tac out java html ati
爬蟲感覺挺有意思的,寫一個最簡單的抓取百度首頁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 try19 {20 // 將string轉成url對象21 URL realUrl = new URL(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 finally41 {42 try43 {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爬取百度首頁原始碼