java爬取百度首頁原始碼

來源:互聯網
上載者:User

標籤:一個   異常   儲存   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爬取百度首頁原始碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.