《小程序---利用jsoup解析CSDN博客信息》

来源:互联网 发布:java生成条码 编辑:程序博客网 时间:2024/05/21 18:31
[java] view plaincopyprint?
  1. package com.fenghuo.html;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.jsoup.Connection;  
  6. import org.jsoup.Jsoup;  
  7. import org.jsoup.nodes.Document;  
  8. import org.jsoup.nodes.Element;  
  9. import org.jsoup.select.Elements;  
  10.   
  11. public class AnalyzeHtml {  
  12.     /** 
  13.      * Example program to list links from a URL. 
  14.      */  
  15.   
  16.     public static void main(String[] args) throws IOException {  
  17.         String csdn = "http://blog.csdn.net";  
  18.         String blog = "http://blog.csdn.net/w695050167";  
  19.         String url = blog + "?viewmode=list";  
  20.   
  21.         Connection connection = Jsoup.connect(url);  
  22.         connection.timeout(500);//设置连接超时时间  
  23.         //给服务器发消息头,告诉服务器,俺不是java程序。CSDN不允许java程序访问  
  24.         connection.header("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");  
  25.         Document doc = connection.get();//获取返回的html的document对象  
  26.           
  27.         //解析document对象  
  28.         Elements links = doc.select(".link_title");  
  29.   
  30.         for (Element e : links) {  
  31.             if (e.getAllElements().size() == 2) {  
  32.                   
  33.                 Element ae = e.select("a[href]").first();  
  34.                 String href = ae.attr("href");  
  35.                 System.out.println(csdn + href);  
  36.   
  37.                 String text = e.text();  
  38.                 System.out.println(text);  
  39.             }  
  40.         }  
  41.   
  42.     }  
  43.   
  44. }  
0 0