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,我们需要他们提供的返回值提供数据进行判断等。从而进行使用啦...

 

posted @ 2014-11-14 15:36  全力以赴001  阅读(4715)  评论(0编辑  收藏  举报