java解析網頁的內容


有時候,我們需要在java程序中獲取一個連接,然后解析連接后,獲取連接返回的內容結果來解析。准確的說是解析一個鏈接。

以下代碼時解析百度首頁的鏈接,獲取的html代碼的效果:

  

 1      public static List<String> getURLCollection(String address){
 2             List<String> list = new LinkedList<String>();
 3             try{
 4                 URL url = new URL(address);
 5                 URLConnection conn = url.openConnection();
 6                 conn.connect();
 7                 InputStream in = conn.getInputStream();
 8                 InputStreamReader input = new InputStreamReader(in, "UTF-8");
 9                 BufferedReader buf = new BufferedReader(input);
10                 String nextLine = buf.readLine();
11      
12                 while(nextLine != null){
13                     list.add(nextLine);
14                     nextLine = buf.readLine();
15                 }
16             }catch(Exception e){
17                 e.printStackTrace();
18             }
19             return list;
20         }
21      
22         public static void main(String[] args){
23             String address = "http://www.baidu.com";
24             List<String> list = getURLCollection(address);
25             String buf = "";
26             for(String str : list){
27                 buf+=str+"\n";
28             }
29           
30             System.out.println(buf);
31         }

 

效果如果:

這樣就將百度的html的代碼抓取出來了哈。

話說有這個有神馬用?

舉個列子吧,比如我們訪問第三方鏈接的時候,第三方返回一段xml,我們需要他們提供的返回值提供數據進行判斷等。從而進行使用啦...

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM