java 爬取网页页面内容

来源:互联网 发布:python中sys.argv 编辑:程序博客网 时间:2024/05/11 04:31

根据 请求URL 指定要爬取的页面

再通过相应请求为200(请求相应成功)进行下一步操作

通过IO操作将页面输出


上源码:

package com.fussent.test;
import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

    public class WebPathSource {

        public static void main(String args[]){    

            URL url;

            int responsecode;

            HttpURLConnection urlConnection;

            BufferedReader reader;

            String line;

            try{

                //生成一个URL对象,要获取源代码的网页地址为:http://www.sina.com.cn

                url=new URL("http://www.sina.com.cn");

                //打开URL

                urlConnection = (HttpURLConnection)url.openConnection();

                //获取服务器响应代码

                responsecode=urlConnection.getResponseCode();

                if(responsecode==200){

                    //得到输入流,即获得了网页的内容

                    reader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));

                    while((line=reader.readLine())!=null){

                        System.out.println(line);

                    }

                }

                else{

                    System.out.println("获取不到网页的源码,服务器响应代码为:"+responsecode);

                }

            }

            catch(Exception e){

                System.out.println("获取不到网页的源码,出现异常:"+e);

            }

        }

    }


0 0
原创粉丝点击