Java网络爬虫

1.网络爬虫

网络爬虫(Web crawler),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本

2.环境准备

创建Maven工程itcast-crawler-first并给pom.xml加入依赖

<dependencies>
    <!-- HttpClient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>
 
    <!-- 日志 -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.25</version>
    </dependency>
</dependencies>

加入log4j.properties

log4j.rootLogger=DEBUG,A1
log4j.logger.cn.itcast = DEBUG
 
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

4.HttpClient

网络爬虫就是用程序帮助我们访问网络上的资源,我们一直以来都是使用HTTP协议访问互联网的网页,网络爬虫需要编写程序,在这里使用同样的HTTP协议访问网页。

这里我们使用Java的HTTP协议客户端 HttpClient这个技术,来实现抓取网页数据。

开始第一个最简单的爬虫,爬取百度首页:http://www.baidu.com

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://www.baidu.com");
    CloseableHttpResponse response = httpClient.execute(httpGet);
    if (response.getStatusLine().getStatusCode() == 200) {
        String content = EntityUtils.toString(response.getEntity(), "UTF-8");
        System.out.println(content);
    }
}

爬取结果:

GET请求

访问京东官网,请求url地址:http://www.jd.com/

public static void main(String[] args) throws IOException {
    //创建HttpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //创建HttpGet请求
    HttpGet httpGet = new HttpGet("http://www.jd.com/");

    CloseableHttpResponse response = null;
    try {
        //使用HttpClient发起请求
        response = httpClient.execute(httpGet);

        //判断响应状态码是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            //如果为200表示请求成功,获取返回数据
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            //打印数据长度
            System.out.println(content);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //释放连接
        if (response == null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            httpClient.close();
        }
    }
}

爬取结果:

带参数的GET请求

在传智中搜索学习视频,地址为:http://yun.itheima.com/search?keys=Java

public class HttpGetParamsTest {

    public static void main(String[] args) throws URISyntaxException {
        //创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpGet,设置访问地址  https://yun.itheima.com/search?key=Java
        //设置参数
        URIBuilder uriBuilder = new URIBuilder("https://yun.itheima.com/search");
        uriBuilder.addParameter("keys","Java");
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        CloseableHttpResponse response = null;
        try {
            //使用httpClient发起请求,获取response
            response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                String content = EntityUtils.toString(entity, "utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

POST请求

public class HttpPostTest {

    public static void main(String[] args) {
        //创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建 httpPost,设置访问地址
        HttpPost httpPost = new HttpPost("http://www.baidu.com");
        CloseableHttpResponse response = null;
        try {
            //使用httpClient发起请求,获取response
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                String content = EntityUtils.toString(entity, "utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

POST 带参数的

在传智中搜索学习视频,使用POST请求,url地址为:
http://yun.itheima.com/search
url地址没有参数,参数keys=java放到表单中进行提交

public class HttpPostParamsTest {

    public static void main(String[] args) throws Exception {
        //创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建 httpPost,设置访问地址  https://yun.itheima.com/search?keys=Java
        //https://www.baidu.com/s?wd=Java
        HttpPost httpPost = new HttpPost("https://www.baidu.com/s");
        //声明List集合,封装表单中的参数
        List<NameValuePair> pairs = new ArrayList<>();
        //设置氢气地址需要的参数
        pairs.add(new BasicNameValuePair("wd","Java"));
        //创建表单里的Entity对象
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,"utf8");
        //设置表单的Entity对象到Post请求中
        httpPost.setEntity(entity);

        CloseableHttpResponse response = null;
        try {
            //使用httpClient发起请求,获取response
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

链接池

如果每次请求都要创建HttpClient,会有频繁创建和销毁的问题,可以使用连接池来解决这个问题。
测试以下代码,并断点查看每次获取的HttpClient都是不一样的。

public class HttpClientPoolTest {

    public static void main(String[] args) {
        //创建连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //使用连接池管理器发起请求
        doGet(cm);
        doGet(cm);

    }

    private static void doGet(PoolingHttpClientConnectionManager cm) {
        //不是每次创建新的httpClient,而是从连接池中获取httpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
        //设置连接数
        cm.setMaxTotal(100);
        //设置每个主机最大的链接数
        cm.setDefaultMaxPerRoute(10);
        
        HttpGet httpGet = new HttpGet("http://www.itcast.cn");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(),"utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
            if(response!=null){
                try {
                    response.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                //不能关闭httpClient。由连接池管理httpClient
                //httpClient.close()
            }

        }
    }
}

请求信息的配置

有时候因为网络,或者目标服务器的原因,请求需要更长的时间才能完成,我们需要自定义相关时间

public class HttpConfigTest {

    public static void main(String[] args) {
        //创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpGet,设置访问地址
        HttpGet httpGet = new HttpGet("http://www.itcast.cn");
        
        //配置请求信息
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(1000)//设置连接的最长时间 毫秒
                .setConnectionRequestTimeout(500) //设置获取连接的最长时间 毫秒
                .setSocketTimeout(10*1000) //设置数据传输的时间 毫秒
                .build();
        //给请求设置请求信息
        httpGet.setConfig(config);
        
        CloseableHttpResponse response = null;
        try {
            //使用httpClient发起请求,获取response
            response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = response.getEntity();
                String content = EntityUtils.toString(entity, "utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值