Z01 - 002、阶段Ⅰ:Java版爬虫开发基础概念

0、本章学习目录大纲 - 爬虫开发基础

初学耗时:??h

注:CSDN手机端暂不支持章节内链跳转,但外链可用,更好体验还请上电脑端。

一、爬虫基本概念
  1.1  三大模块。
  1.2  执行流程。
  1.3  爬虫的作用。
  1.4  爬虫的分类。
  1.5  回顾http请求。
  1.6  回顾http响应。
  1.7  状态码。
  1.8  创建父类项目。

二、发送请求 - 原生JDK
    2.1  创建Module子项目。
    2.2  get。
    2.3  post。

三、发送请求 - httpClient
  3.1  发送步骤。
  3.2  创建包名、类名。
  3.3  导入jar包。
  3.4  get 。
  3.5  post 。

四、解析数据
    4.1  如何解析HTML文档?
    4.2  创建包名、类名。
    4.3  如何使用jsoup?
    4.4  了解:如何获取document对象?
    4.5  使用jsoup解析数据

五、保存数据 - 后续讲解



ギ 舒适区ゾ || ♂ 累觉无爱 ♀





一、爬虫基本概念

  1.1 ~  三大模块。

  alt

  1.2 ~  执行流程。

  alt

  1.3 ~  爬虫的作用。

  alt

  1.4 ~  爬虫的分类。

  alt

  1.5 ~  回顾http请求。

  alt

  1.6 ~  回顾http响应。

  alt

  1.7 ~  状态码。
200、一切正常。
302、重定向。
304:本地缓存。
400、请求参数错误。
404、资源路径错误。
500、服务器内部源代码错误。
  1.8 ~  创建父类项目。
    1.8.1 .   项目开发工具:idea【网盘提供2018永久破解版下载】。
    1.8.2 .   创建父类project项目:yltt_projects。
    1.8.3 .   删除src。


3D环绕特效:丢手绢!

- - - - - - - - - - - - - - - - - - - - - - - - - - - -


二、发送请求 - 原生JDK

  2.1 ~ 创建Module子项目.
    2.1.1 .   创建Module子项目:gossip_spider_base。
    2.1.2 .   创建包名:com.yltt.spider.jdk。
    2.1.3 .   创建类名:JDKGet。
    2.1.4 .   创建类名:JDKPost。

    alt

  2.2 ~ get。
// 模拟 原生JDK发送get请求
public class JDKGet {

    public static void main(String[] args) throws Exception {
        //1. 确定首页的URL
        String indexUrl = "http://www.itcast.cn";//注意安全协议
        //2. 将字符串的url转换成url对象
        URL url = new URL(indexUrl);

        //3. 打开连接, 获取和远程地址的连接对象
        HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();

        //4. 设置相关的参数: 请求参数 ,请求方式
        urlConnection.setRequestMethod("GET"); // 设置请求方式的时候, 一样要大写, 默认请求方式是GET

        //5. 发送请求,  : 类似于socket发送请求
        InputStream in = urlConnection.getInputStream(); // 获取输入流的时候, 就相当于发送请求

        //6. 获取数据
        int len = 0;
        byte[] b = new byte[1024];
        while( (len = in.read(b))!= -1 ){

            System.out.println(new String(b,0,len)); // string注意是lang包的下

        }

        //7. 释放资源
        in.close();
    }
    
}
  2.3 ~ post。
// 模拟原生jdk发送post请求
public class JDKPost {

    public static void main(String[] args) throws  Exception {
        //1. 确定首页url
        String indexUrl = "http://www.itcast.cn";

        //2. 将字符串的url转换成url对象
        URL url = new URL(indexUrl);

        //3. 打开连接, 获取连接对象
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        //4. 设置参数: 请求参数, 请求方式
        urlConnection.setRequestMethod("POST");
        // 注意: 获取输出流的时候, 先将输出流打开, 原生jdk默认将输出流禁用
        urlConnection.setDoOutput(true);
        OutputStream out = urlConnection.getOutputStream();

        out.write("username=zs&password=123".getBytes());

        //5. 发送请求, 获取输入流
        InputStream in = urlConnection.getInputStream();

        //6. 获取数据
        int len = 0;
        byte[] b = new byte[1024];
        while( (len = in.read(b))!=-1 ){
            System.out.println(new String(b,0,len));
        }

        //7. 释放资源
        in.close();
        out.close();
    }
    
}

小贴士:idea一次性自动导包。
setting -> General -> Auto Import
alt


3D环绕特效:丢手绢!

- - - - - - - - - - - - - - - - - - - - - - - - - - - -




三、发送请求 - httpClient

  3.1 ~  发送步骤。

httpClient是Apache提供的一个开源的,专门用来发送http请求的,效率非常高。

alt

  3.2 ~  创建包名、类名。
    3.2.1 .   创建包名:com.yltt.spider.httpclient。
    3.2.2 .   创建类名:HTTPClientGet。
    3.2.2 .   创建类名:HTTPClientPost。

    alt

  3.3 ~  导入jar包。
    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.4</version>
        </dependency>
    </dependencies>
  3.4 ~  get。
// 模拟使用httpClient发送get请求
public class HTTPClientGet {
    
    public static void main(String[] args) throws Exception {
        //1. 确定首页url
        String indexUrl  = "http://www.itcast.cn?username=zrk&password=123";

        //2. 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault(); // 固定 代码获取httpClient对象

        //3. 设置参数:  请求参数, 请求方式 , 请求头
        //HttpGet 可以将其看做是get请求的请求对象(request)
        HttpGet httpGet = new HttpGet(indexUrl);

        // setHreader  和 addHeader 区别:
        // setHreader主要是为一个key对应着一个value的请求头进行设置的
        // addHeader 主要是为一个key对应着多个value的请求头进行设置的
        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36");

        //4. 发送请求, 获取响应对象
        // response : 包含了响应行的数据, 响应头的内容, 响应体
        CloseableHttpResponse response = httpClient.execute(httpGet);

        //5. 获取数据
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(statusCode);
        if(statusCode == 200){
            //请求成功了
            //5.1 获取响应头
            Header[] headers = response.getHeaders("Content-Type");
            String value = headers[0].getValue();
            System.out.println(value);

            //5.2 获取响应体
            HttpEntity entity = response.getEntity();// 获取响应体
            // 如果响应体中数据是文本数据类型的, 那么提供了工具类, 帮助获取文本信息
            String html = EntityUtils.toString(entity, "UTF-8");
            System.out.println(html);
        }

        //6. 释放资源
        httpClient.close();
    }
    
}
  3.5 ~  post。
// 模拟 使用httpClient发送post请求
public class HTTPClientPost {

    public static void main(String[] args) throws Exception {
        //1. 确定首页的url
        String indexUrl = "http://www.itcast.cn"; // 千万别丢了协议 http://

        //2. 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //3. 设置参数: 请求参数, 请求头, 请求方式
        HttpPost httpPost = new HttpPost(indexUrl);
        //httpPost.setHeader("","");
        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
        list.add(new BasicNameValuePair("username","xiaojuhua"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
        httpPost.setEntity(entity);

        //4. 发送请求, 获取响应对象
        CloseableHttpResponse response = httpClient.execute(httpPost);

        //5. 获取数据
        int statusCode = response.getStatusLine().getStatusCode();
        if(statusCode == 200 ){
            //请求成功
            //5.1 获取响应头
            Header[] headers = response.getHeaders("Content-Type");
            System.out.println(headers[0].getValue());
            //5.2 获取响应体
            HttpEntity entity1 = response.getEntity();
            System.out.println(EntityUtils.toString(entity1,"utf-8"));
        }

        //6. 释放资源
        httpClient.close();
    }
    
}

3D环绕特效:丢手绢!

- - - - - - - - - - - - - - - - - - - - - - - - - - - -




四、解析数据

  4.1 ~  如何解析HTML文档?

  alt
  alt

  4.2 ~  创建包名、类名。
    4.2.1 .   创建包名:com.yltt.spider.jsoup。
    4.2.2 .   创建类名:JsoupByDocument。
    4.2.3 .   创建类名:JsoupParse。

    alt

  4.3 ~  如何使用jsoup?
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.3</version>
        </dependency>
  4.4 ~  了解:如何获取document对象?

alt

// 演示,使用jsoup获取document对象的方式
public class JsoupByDocument {

    public static void main(String[] args) throws IOException {
        //1. 获取的方式一: 最常使用的一种
        String html = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>使用jsoup获取document对象的方式一</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "\n" +
                "</body>\n" +
                "</html>";
        Document document1 = Jsoup.parse(html);

        String title = document1.title();
        System.out.println(title);

        //2. 获取document方式二:  最简单的方式
        // 一般只是在测试的时候会使用
        String indexUrl = "http://www.itcast.cn";
        Document document2 = Jsoup.connect(indexUrl).get();
        System.out.println(document2);

        //3. 可以加载本地的HTML文档, 转换成document对象
        //Document document = Jsoup.parse(new File(""), "UTF-8");

        //4. 可以将HTML的片段转换成document对象的
        //Document document4 = Jsoup.parseBodyFragment("<a href = 'http://www.itcast.cn'>访问传智播客的首页</a>");
        Document document4 = Jsoup.parse("<a href = 'http://www.itcast.cn'>访问传智播客的首页</a>");
        System.out.println(document4.text());
    }
    
}
  4.5 ~  使用jsoup解析数据。
    4.5.1 .   基本了解。

    alt

    4.5.2 .   需求:获取传智播客目前开设的那些课程。
    4.5.3 .   使用原生js的方式获取。
    4.5.4 .   使用选择器的方式来获取课程信息。
public class JsoupParse {
    //原生js: 获取传智播客的课程信息
    @Test
    public void jsoupByJs() throws Exception {
        String indexUrl = "http://www.itcast.cn";
        //使用最简单的方式, 获取document
        Document document = Jsoup.connect(indexUrl).get();

        //2. 如何解析首页数据
        Elements divEls = document.getElementsByClass("nav_txt");
        Element div = divEls.get(0);

        Elements ulEls = div.getElementsByTag("ul");
        Element ul = ulEls.get(0);

        Elements liEls = ul.getElementsByTag("li");

        for (Element liEl : liEls) {
            Elements aEls = liEl.getElementsByTag("a");
            Element a = aEls.get(0);
            String text = a.text();
            System.out.println(text);
        }
    }

    //选择器: 获取传智播客的课程信息
    @Test
    public void jsoupBySelector() throws Exception {
        String indexUrl = "http://www.itcast.cn";
        //使用最简单的方式, 获取document
        Document document = Jsoup.connect(indexUrl).get();

        //2. 使用选择器获取课程信息

        Elements aEls = document.select(".nav_txt>ul>li>a");

        for (Element aEl : aEls) {
            System.out.println(aEl.text());
        }
    }
}
    4.5.5 .   总结。

    alt


3D环绕特效:丢手绢!

- - - - - - - - - - - - - - - - - - - - - - - - - - - -




五、保存数据 - 后续讲解

alt



3D环绕特效:丢手绢!

- - - - - - - - - - - - - - - - - - - - - - - - - - - -



^ 至此,Java版爬虫开发基础概念完成。


- - - - - - - - - - - - - - - - - - - - - - - - - - - -


※ 世间诱惑何其多,坚定始终不动摇。

千里修书只为墙,让他三尺又何妨?
万里长城今犹在,不见当年秦始皇。
alt



3D环绕特效:丢手绢!

- - - - - - - - - - - - - - - - - - - - - - - - - - - -


注:CSDN手机端暂不支持章节内链跳转,但外链可用,更好体验还请上电脑端。

我知道我的不足,我也知道你的挑剔,但我就是我,不一样的烟火,谢谢你的指指点点,造就了我的点点滴滴:)!



3D环绕特效:丢手绢!


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值