liushisaonian

  网络爬虫

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

网络爬虫介绍

在大数据时代,信息的采集是一项重要的工作,而互联网中的数据是海量的,如果单纯靠人力进行信息采集,不仅低效繁琐,搜集的成本也会提高。如何自动高效地获取互联网中我们感兴趣的信息并为我们所用是一个重要的问题,而爬虫技术就是为了解决这些问题而生的。

 

网络爬虫(Web crawler)也叫做网络机器人,可以代替人们自动地在互联网中进行数据信息的采集与整理。它是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本,可以自动采集所有其能够访问到的页面内容,以获取相关数据。

 

从功能上来讲,爬虫一般分为数据采集,处理,储存三个部分。爬虫从一个或若干初始网页的URL开始,获得初始网页上的URL,在抓取网页的过程中,不断从当前页面上抽取新的URL放入队列,直到满足系统的一定停止条件。

我们初步认识了网络爬虫,但是为什么要学习网络爬虫呢?只有清晰地知道我们的学习目的,才能够更好地学习这一项知识。在此,总结了4种常见的学习爬虫的原因:

为什么学网络爬虫

  可以实现搜索引擎

我们学会了爬虫编写之后,就可以利用爬虫自动地采集互联网中的信息,采集回来后进行相应的存储或处理,在需要检索某些信息的时候,只需在采集回来的信息中进行检索,即实现了私人的搜索引擎。

  大数据时代,可以让我们获取更多的数据源。

在进行大数据分析或者进行数据挖掘的时候,需要有数据源进行分析。我们可以从某些提供数据统计的网站获得,也可以从某些文献或内部资料中获得,但是这些获得数据的方式,有时很难满足我们对数据的需求,而手动从互联网中去寻找这些数据,则耗费的精力过大。此时就可以利用爬虫技术,自动地从互联网中获取我们感兴趣的数据内容,并将这些数据内容爬取回来,作为我们的数据源,再进行更深层次的数据分析,并获得更多有价值的信息。

  可以更好地进行搜索引擎优化(SEO)。

对于很多SEO从业者来说,为了更好的完成工作,那么就必须要对搜索引擎的工作原理非常清楚,同时也需要掌握搜索引擎爬虫的工作原理。

而学习爬虫,可以更深层次地理解搜索引擎爬虫的工作原理,这样在进行搜索引擎优化时,才能知己知彼,百战不殆。

环境准备

 1 <dependencies>
 2     <!-- HttpClient -->
 3     <dependency>
 4         <groupId>org.apache.httpcomponents</groupId>
 5         <artifactId>httpclient</artifactId>
 6         <version>4.5.3</version>
 7     </dependency>
 8 
 9     <!-- 日志 -->
10     <dependency>
11         <groupId>org.slf4j</groupId>
12         <artifactId>slf4j-log4j12</artifactId>
13         <version>1.7.25</version>
14     </dependency>
15 </dependencies>

1.   HttpClient

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

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

 

 1 public static void main(String[] args) throws Exception {
 2         //1. 打开浏览器,创建HttpClient对象
 3         CloseableHttpClient httpClient = HttpClients.createDefault();
 4 
 5         //2. 输入网址,发起get请求创建HttpGet对象
 6         HttpGet httpGet = new HttpGet("http://www.mybatis.org/mybatis-3/zh/index.html");
 7 
 8         //3.按回车,发起请求,返回响应,使用HttpClient对象发起请求
 9         CloseableHttpResponse response = httpClient.execute(httpGet);
10 
11         //4. 解析响应,获取数据
12         //判断状态码是否是200
13         if (response.getStatusLine().getStatusCode() == 200) {
14             HttpEntity httpEntity = response.getEntity();
15             String content = EntityUtils.toString(httpEntity, "utf8");
16 
17             System.out.println(content);
18         }
19     }

 

 GET请求

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

        //创建HttpGet对象,设置url访问地址
        HttpGet httpGet = new HttpGet("http://www.mybatis.org/mybatis-3/zh/index.html");

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

            //解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭response
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

 GET带参数请求

 1 public static void main(String[] args) throws Exception {
 2         //创建HttpClient对象
 3         CloseableHttpClient httpClient = HttpClients.createDefault();
 4 
 5         //设置请求地址是:http://yun.itheima.com/search?keys=Java
 6         //创建URIBuilder
 7         URIBuilder uriBuilder = new URIBuilder("http://www.mybatis.org/mybatis-3/zh/index.html");
 8         //设置参数
 9         uriBuilder.setParameter("keys","Java");
10 
11         //创建HttpGet对象,设置url访问地址
12         HttpGet httpGet = new HttpGet(uriBuilder.build());
13 
14         System.out.println("发起请求的信息:"+httpGet);
15 
16         CloseableHttpResponse response = null;
17         try {
18             //使用HttpClient发起请求,获取response
19              response = httpClient.execute(httpGet);
20 
21             //解析响应
22             if (response.getStatusLine().getStatusCode() == 200) {
23                 String content = EntityUtils.toString(response.getEntity(), "utf8");
24                 System.out.println(content.length());
25             }
26 
27         } catch (IOException e) {
28             e.printStackTrace();
29         }finally {
30             //关闭response
31             try {
32                 response.close();
33             } catch (IOException e) {
34                 e.printStackTrace();
35             }
36             try {
37                 httpClient.close();
38             } catch (IOException e) {
39                 e.printStackTrace();
40             }
41         }
42     }

 

POST请求

 1 public static void main(String[] args)  {
 2         //创建HttpClient对象
 3         CloseableHttpClient httpClient = HttpClients.createDefault();
 4 
 5         //创建HttpPost对象,设置url访问地址
 6         HttpPost httpPost = new HttpPost("http://www.mybatis.org/mybatis-3/zh/index.html");
 7 
 8         CloseableHttpResponse response = null;
 9         try {
10             //使用HttpClient发起请求,获取response
11              response = httpClient.execute(httpPost);
12 
13             //解析响应
14             if (response.getStatusLine().getStatusCode() == 200) {
15                 String content = EntityUtils.toString(response.getEntity(), "gbk");
16                 System.out.println(content.length());
17             }
18 
19         } catch (IOException e) {
20             e.printStackTrace();
21         }finally {
22             //关闭response
23             try {
24                 response.close();
25             } catch (IOException e) {
26                 e.printStackTrace();
27             }
28             try {
29                 httpClient.close();
30             } catch (IOException e) {
31                 e.printStackTrace();
32             }
33         }
34     }

 

 POST带参数请求

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

        //创建HttpPost对象,设置url访问地址
        HttpPost httpPost = new HttpPost("http://www.mybatis.org/mybatis-3/zh/index.html");

        //声明List集合,封装表单中的参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        //设置请求地址是:http://yun.itheima.com/search?keys=Java
        params.add(new BasicNameValuePair("keys","Java"));

        //创建表单的Entity对象,第一个参数就是封装好的表单数据,第二个参数就是编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"utf8");

        //设置表单的Entity对象到Post请求中
        httpPost.setEntity(formEntity);

        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.length());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭response
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

池管理

 1 public static void main(String[] args)  {
 2         //创建HttpClient对象
 3         CloseableHttpClient httpClient = HttpClients.createDefault();
 4 
 5         //创建HttpGet对象,设置url访问地址
 6         HttpGet httpGet = new HttpGet("http://www.baid.com");
 7 
 8         //配置请求信息
 9         RequestConfig config = RequestConfig.custom().setConnectTimeout(1000)   //创建连接的最长时间,单位是毫秒
10                 .setConnectionRequestTimeout(500)   //设置获取连接的最长时间,单位是毫秒
11                 .setSocketTimeout(10*1000)      //设置数据传输的最长时间,单位是毫秒
12                 .build();
13 
14         //给请求设置请求信息
15         httpGet.setConfig(config);
16 
17         CloseableHttpResponse response = null;
18         try {
19             //使用HttpClient发起请求,获取response
20              response = httpClient.execute(httpGet);
21 
22             //解析响应
23             if (response.getStatusLine().getStatusCode() == 200) {
24                 String content = EntityUtils.toString(response.getEntity(), "utf8");
25                 System.out.println(content.length());
26             }
27 
28         } catch (IOException e) {
29             e.printStackTrace();
30         }finally {
31             //关闭response
32             try {
33                 response.close();
34             } catch (IOException e) {
35                 e.printStackTrace();
36             }
37             try {
38                 httpClient.close();
39             } catch (IOException e) {
40                 e.printStackTrace();
41             }
42         }
43     }
public static void main(String[] args) {
        //创建连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

        //设置最大连接数
        cm.setMaxTotal(100);

        //设置每个主机的最大连接数
        cm.setDefaultMaxPerRoute(10);

        //使用连接池管理器发起请求
        doGet(cm);
        doGet(cm);
    }

    private static void doGet(PoolingHttpClientConnectionManager cm) {
        //不是每次创建新的HttpClient,而是从连接池中获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

        HttpGet httpGet = new HttpGet("http://www.mybatis.org/mybatis-3/zh/index.html");

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);

            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");

                System.out.println(content.length());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //不能关闭HttpClient,由连接池管理HttpClient
                //httpClient.close();
            }
        }

    }

 

 

AAA

AAAAaaaa

分类:

技术点:

相关文章: