网络爬虫入门

1. 网络爬虫

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

1.1. 爬虫入门程序

1.1.1. 环境准备

  • JDK1.8
  • IntelliJ IDEA
  • IDEA自带的Maven

1.1.2. 环境准备

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

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.36</version>
    <scope>test</scope>
</dependency>

1.1.3. 加入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

1.1.4. 编写代码

编写最简单的爬虫,抓取我的csdn博客首页:https://terence.blog.csdn.net

/**
 * 入门测试
 * @throws IOException
 */
@Test
public void test1() throws IOException {
    //1. 打开浏览器,创建HttpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    
    //2. 输入网址,发起get请求创建HttpGet对象
    HttpGet httpGet = new HttpGet("https://terence.blog.csdn.net");
    
    //3. 按回车发起请求,返回响应
    CloseableHttpResponse response = httpClient.execute(httpGet);
   
    //4. 解析响应,
    //判断状态码是否是200
    if(response.getStatusLine().getStatusCode()==200){
        HttpEntity httpEntity = response.getEntity();
        String content = EntityUtils.toString(httpEntity, "utf8");
        System.out.println(content);
    }
}

测试结果:可以获取到页面数据

2. 网络爬虫

2.1. 网络爬虫介绍

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

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

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

2.2. 为什么学网络爬虫

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

  • 可以实现搜索引擎
    我们学会了爬虫编写之后,就可以利用爬虫自动地采集互联网中的信息,采集回来后进行相应的存储或处理,在需要检索某些信息的时候,只需在采集回来的信息中进行检索,即实现了私人的搜索引擎。
  • 大数据时代,可以让我们获取更多的数据源。
    在进行大数据分析或者进行数据挖掘的时候,需要有数据源进行分析。我们可以从某些提供数据统计的网站获得,也可以从某些文献或内部资料中获得,但是这些获得数据的方式,有时很难满足我们对数据的需求,而手动从互联网中去寻找这些数据,则耗费的精力过大。此时就可以利用爬虫技术,自动地从互联网中获取我们感兴趣的数据内容,并将这些数据内容爬取回来,作为我们的数据源,再进行更深层次的数据分析,并获得更多有价值的信息。
  • 可以更好地进行搜索引擎优化(SEO)。
    对于很多SEO从业者来说,为了更好的完成工作,那么就必须要对搜索引擎的工作原理非常清楚,同时也需要掌握搜索引擎爬虫的工作原理。
    而学习爬虫,可以更深层次地理解搜索引擎爬虫的工作原理,这样在进行搜索引擎优化时,才能知己知彼,百战不殆。
  • 有利于就业。
    从就业来说,爬虫工程师方向是不错的选择之一,因为目前爬虫工程师的需求越来越大,而能够胜任这方面岗位的人员较少,所以属于一个比较紧缺的职业方向,并且随着大数据时代和人工智能的来临,爬虫技术的应用将越来越广泛,在未来会拥有很好的发展空间。

3. HttpClient

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

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

3.1. GET请求

访问我的csdn博客首页,请求url地址:https://terence.blog.csdn.net

/**
 * Get请求
 *
 * @throws IOException
 */
@Test
public void test2() throws IOException {
    //创建HttpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //创建HttpGet对象,设置url访问地址
    HttpGet httpGet = new HttpGet("https://terence.blog.csdn.net");

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

        //解析响应,
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity httpEntity = response.getEntity();
            String content = EntityUtils.toString(httpEntity, "utf8");
            System.out.println(content);
            System.out.println(content.length());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //释放连接
        if (response != null) {
            response.close();
        }
        if(httpClient!=null){
            httpClient.close();
        }
    }
}

请求结果

3.2. 带参数的GET请求

 访问csdn获取文章链接的接口,请求url地址: 

https://blog.csdn.net/community/home-api/v1/get-business-list?page=1&size=100&businessType=blog&username=qq_39997939

/**
 * 带参数到Get请求
 *
 * @throws IOException
 * @throws URISyntaxException
 */
@Test
public void test3() throws IOException, URISyntaxException {
    //创建HttpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //设置请求地址是:https://blog.csdn.net/community/home-api/v1/get-business-list?page=1&size=100&businessType=blog&username=qq_39997939
    //创建URIBuilder
    URIBuilder uriBuilder = new URIBuilder("https://blog.csdn.net/community/home-api/v1/get-business-list");
    uriBuilder.setParameter("page", "1");
    uriBuilder.setParameter("size", "100");
    uriBuilder.setParameter("businessType", "blog");
    uriBuilder.setParameter("username", "qq_39997939");

    //创建HttpGet对象,设置url访问地址
    HttpGet httpGet = new HttpGet(uriBuilder.build());
    System.out.println("发起请求的信息:" + httpGet);
    CloseableHttpResponse response = null;
    try {
        //使用HttpClient发起请求,获取response
        response = httpClient.execute(httpGet);

        //解析响应,
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity httpEntity = response.getEntity();
            String content = EntityUtils.toString(httpEntity, "utf8");
            System.out.println(content);
            System.out.println(content.length());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //释放连接
        if (response != null) {
            response.close();
        }
        if(httpClient!=null){
            httpClient.close();
        }
    }
}

请求结果

3.3. POST请求

使用POST访问传智官网,请求url地址:

http://www.itcast.cn/

/**
 * post请求测试
 *
 * @throws IOException
 */
@Test
public void test4() throws IOException {
    //创建HttpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //创建HttpGet对象,设置url访问地址
    HttpPost httpGet = new HttpPost("https://blog.csdn.net/community/home-api/v1/get-business-list");

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

        //解析响应,
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity httpEntity = response.getEntity();
            String content = EntityUtils.toString(httpEntity, "utf8");
            System.out.println(content);
            System.out.println(content.length());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //释放连接
        if (response != null) {
            response.close();
        }
        if(httpClient!=null){
            httpClient.close();
        }
    }
}

请求结果:

3.4. 带参数的POST请求

在传智中搜索学习视频,使用POST请求,url地址为:

http://yun.itheima.com/search

url地址没有参数,参数keys=java放到表单中进行提交

/**
 * 带参数到post请求
 *
 * @throws IOException
 */
@Test
public void test5() throws IOException {
    //创建HttpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();

    //创建HttpGet对象,设置url访问地址
    HttpPost httpPost = new HttpPost("http://yun.itheima.com/search");

    //声明List集合,封装表单中的参数
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("keys", "java"));

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

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

    //设置表单的Entity对象到Post域中
    CloseableHttpResponse response = null;
    try {
        //使用HttpClient发起请求,获取response
        response = httpClient.execute(httpPost);

        //解析响应,
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity httpEntity = response.getEntity();
            String content = EntityUtils.toString(httpEntity, "utf8");
            System.out.println(content);
            System.out.println(content.length());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //释放连接
        if (response != null) {
            response.close();
        }
        if(httpClient!=null){
            httpClient.close();
        }
    }
}

请求结果

 3.5. 连接池

如果每次请求都要创建HttpClient,会有频繁创建和销毁的问题,可以使用连接池来解决这个问题。

测试以下代码,并断点查看每次获取的HttpClient都是不一样的。

/**
 * 连接池测试
 */
@Test
public void test6() {
    //创建连接池管理器
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

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

    //设置每个主机的并发数
    cm.setDefaultMaxPerRoute(20);

    //使用连接池管理器发起请求
    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.itcast.cn/");
    CloseableHttpResponse response = null;

    try {
        response = httpClient.execute(httpGet);

        // 判断状态码是否是200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 解析数据
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(content.length());
        }

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

3.6. 请求参数

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

/**
 * 请求参数
 */
@Test
public void test7(){
    //创建HttpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();

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

    //设置请求参数
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(1000)//设置创建连接的最长时间
            .setConnectionRequestTimeout(500)//设置获取连接的最长时间
            .setSocketTimeout(10 * 1000)//设置数据传输的最长时间
            .build();

    httpGet.setConfig(requestConfig);

    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();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4. Jsoup

我们抓取到页面之后,还需要对页面进行解析。可以使用字符串处理工具解析页面,也可以使用正则表达式,但是这些方法都会带来很大的开发成本,所以我们需要使用一款专门解析html页面的技术。

4.1. jsoup介绍

jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据。

jsoup的主要功能如下:

1.从一个URL,文件或字符串中解析HTML;

2.可操作HTML元素、属性、文本;

3.使用DOM或CSS选择器来查找、取出数据;

先加入Jsoup依赖:

<!--Jsoup-->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.10.3</version>
</dependency>
<!--工具-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

4.2. jsoup解析

4.2.1. 解析url

Jsoup可以直接输入url,它会发起请求并获取数据,封装为Document对象

/**
 * Jsoup解析Url
 * @throws Exception
 */
@Test
public void testJsoupUrl() throws Exception {
    //解析url地址
    Document document = Jsoup.parse(new URL("http://www.itcast.cn/"), 1000);

    //获取title的内容
    Element title = document.getElementsByTag("title").first();
    System.out.println(title.text());
}

PS:虽然使用Jsoup可以替代HttpClient直接发起请求解析数据,但是往往不会这样用,因为实际的开发过程中,需要使用到多线程,连接池,代理等等方式,而jsoup对这些的支持并不是很好,所以我们一般把jsoup仅仅作为Html解析工具使用

4.2.2. 解析字符串

先准备以下jsoupTest.html文件

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>传智播客官网-一样的教育,不一样的品质</title>
</head>
<body>
<div class="city">
    <h3 id="city_bj">北京中心</h3>
    <fb:img src="/2018czgw/images/slogan.jpg" class="slogan"/>
    <div class="city_in">
        <div class="city_con" style="display: none;">
            <ul>
                <li id="test" class="class_a class_b">
                    <a href="http://www.itcast.cn" target="_blank">
                        <span class="s_name">北京</span>
                    </a>
                </li>
                <li>
                    <a href="http://sh.itcast.cn" target="_blank">
                        <span class="s_name">上海</span>
                    </a>
                </li>
                <li>
                    <a href="http://gz.itcast.cn" target="_blank">
                        <span abc="123" class="s_name">广州</span>
                    </a>
                </li>
                <ul>
                    <li>天津</li>
                </ul>
            </ul>
        </div>
    </div>
</div>
</body>
</html>

Jsoup可以直接输入字符串,并封装为Document对象

/**
 * Jsoup解析字符串
 * @throws Exception
 */
@Test
public void testJsoupString() throws Exception {
    //读取文件获取
    String html = FileUtils.readFileToString(new File("/Users/terence/develop/IdeaProjects/crawler_demo/jsoupTest.html"), "UTF-8");

    //解析字符串
    Document document = Jsoup.parse(html);

    //获取title的内容
    Element title = document.getElementsByTag("title").first();
    System.out.println(title.text());
}

4.2.3. 解析文件

Jsoup可以直接解析文件,并封装为Document对象

/**
 * Jsoup解析文件
 */
@Test
public void testJsoupHtml() throws Exception {
    //解析文件
    Document document = Jsoup.parse(new File("/Users/terence/develop/IdeaProjects/crawler_demo/jsoupTest.html"), "UTF-8");
    //获取title的内容
    Element title = document.getElementsByTag("title").first();
    System.out.println(title.text());
}

4.2.4. 使用dom方式遍历文档

元素获取

  1. 根据id查询元素getElementById
  2. 根据标签获取元素getElementsByTag
  3. 根据class获取元素getElementsByClass
  4. 根据属性获取元素getElementsByAttribute
/**
 *使用dom方式遍历文档
 */
@Test
public void testDOM() throws IOException {
    //解析文件
    Document doc = Jsoup.parse(new File("/Users/terence/develop/IdeaProjects/crawler_demo/jsoupTest.html"), "UTF-8");

    //获取元素
    //1.	根据id查询元素getElementById
    //Element element = doc.getElementById("city_bj");

    //2.	根据标签获取元素getElementsByTag
    //Element element = doc.getElementsByTag("span").first();

    //3.	根据class获取元素getElementsByClass
    //Element element = doc.getElementsByClass("class_a class_b").first();
    //Element element = doc.getElementsByClass("class_a").first();
    //Element element = doc.getElementsByClass("class_b").first();


    //4.	根据属性获取元素getElementsByAttribute
    //Element element = doc.getElementsByAttribute("abc").first();
    Element element = doc.getElementsByAttributeValue("href", "http://sh.itcast.cn").first();

    //打印元素的内容
    System.out.println("获取到的元素内容是:" + element.text());
}

元素中获取数据

  1. 从元素中获取id
  2. 从元素中获取className
  3. 从元素中获取属性的值attr
  4. 从元素中获取所有属性attributes
  5. 从元素中获取文本内容text
@Test
public void testData() throws Exception {
    //解析文件,获取Document
    Document doc = Jsoup.parse(new File("C:\\Users\\tree\\Desktop\\test.html"), "utf8");

    //根据id获取元素
    Element element = doc.getElementById("test");

    String str = "";

    //元素中获取数据
    //1.	从元素中获取id
    str = element.id();

    //2.	从元素中获取className
    str = element.className();
    //Set<String> classSet = element.classNames();
    //for (String s : classSet ) {
    //    System.out.println(s);
    //}

    //3.	从元素中获取属性的值attr
    //str = element.attr("id");
    str = element.attr("class");

    //4.	从元素中获取所有属性attributes
    Attributes attributes = element.attributes();
    System.out.println(attributes.toString());

    //5.	从元素中获取文本内容text
    str = element.text();

    //打印获取到的内容
    System.out.println("获取到的数据是:" + str);

}

4.2.5. 使用选择器语法查找元素

jsoup elements对象支持类似于CSS (或jquery)的选择器语法,来实现非常强大和灵活的查找功能。这个select 方法在Document, Element,或Elements对象中都可以使用。且是上下文相关的,因此可实现指定元素的过滤,或者链式选择访问。

Select方法将返回一个Elements集合,并提供一组方法来抽取和处理结果。

4.2.6. Selector选择器概述

tagname: 通过标签查找元素,比如:span

#id: 通过ID查找元素,比如:# city_bj

.class: 通过class名称查找元素,比如:.class_a

[attribute]: 利用属性查找元素,比如:[abc]

[attr=value]: 利用属性值来查找元素,比如:[class=s_name]

@Test
public void testSelector() throws Exception {

    //解析html文件,获取Document对象
    Document doc = Jsoup.parse(new File("/Users/terence/develop/IdeaProjects/crawler_demo/jsoupTest.html"), "UTF-8");

    //tagname: 通过标签查找元素,比如:span
    Elements elements = doc.select("span");
    //for (Element element : elements) {
    //    System.out.println(element.text());
    //}

    //#id: 通过ID查找元素,比如:#city_bj
    //Element element = doc.select("#city_bj").first();

    //.class: 通过class名称查找元素,比如:.class_a
    //Element element = doc.select(".class_a").first();

    //[attribute]: 利用属性查找元素,比如:[abc]
    Element element = doc.select("[abc]").first();

    //[attr=value]: 利用属性值来查找元素,比如:[class=s_name]
    Elements elements1 = doc.select("[class=s_name]");
    for (Element element1 : elements1) {
        System.out.println(element1.text());
    }


    //打印结果
    System.out.println("获取到的结果是:" + element.text());
}

4.2.7. Selector选择器组合使用

el#id: 元素+ID,比如: h3#city_bj

el.class: 元素+class,比如: li.class_a

el[attr]: 元素+属性名,比如: span[abc]

任意组合: 比如:span[abc].s_name

ancestor child: 查找某个元素下子元素,比如:.city_con li 查找"city_con"下的所有li

parent > child: 查找某个父元素下的直接子元素,比如:

.city_con > ul > li 查找city_con第一级(直接子元素)的ul,再找所有ul下的第一级li

parent > *: 查找某个父元素下所有直接子元素

@Test
public void testSelector2()throws Exception{
    //解析html文件,获取Document对象
    Document doc = Jsoup.parse(new File("/Users/terence/develop/IdeaProjects/crawler_demo/jsoupTest.html"), "UTF-8");

    //el#id: 元素+ID,比如: h3#city_bj
    Element element = doc.select("h3#city_bj").first();

    //el.class: 元素+class,比如: li.class_a
    element = doc.select("li.class_a").first();

    //el[attr]: 元素+属性名,比如: span[abc]
    element = doc.select("span[abc]").first();

    //任意组合: 比如:span[abc].s_name
    element = doc.select("span[abc].s_name").first();

    //ancestor child: 查找某个元素下子元素,比如:.city_con li 查找"city_con"下的所有li
    Elements elements = doc.select(".city_con li");

    //parent > child: 查找某个父元素下的直接子元素,比如:
    //.city_con > ul > li 查找city_con第一级(直接子元素)的ul,再找所有ul下的第一级li
    elements = doc.select(".city_con > ul > li");

    //parent > *: 查找某个父元素下所有直接子元素
    elements = doc.select(".city_con > ul > *");


    System.out.println("获取到的内容是:"+element.text());

    for (Element element1 : elements) {
        System.out.println("遍历的结果:"+element1.text());
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39997939/article/details/122900012
今日推荐