利用Spring Boot WebMagic MyBatis 爬数据并存入mysql

本文介绍了如何使用Spring Boot结合WebMagic爬取数据,并通过MyBatis将其存入MySQL数据库。在实践中遇到的如SSLException、多线程下Mapper注入为空等问题,也给出了相应的解决方案。
摘要由CSDN通过智能技术生成

一.  WebMagic简介

webmagic是一个开源的Java垂直爬虫框架,目标是简化爬虫的开发流程,让开发者专注于逻辑功能的开发。webmagic的核心非常简单,但是覆盖爬虫的整个流程,也是很好的学习爬虫开发的材料。见官网http://webmagic.io/

二. 快速开始

webmagic使用maven管理依赖,在项目中添加对应的依赖即可使用webmagic:

<dependency>
    <groupId>us.codecraft</groupId>
    <artifactId>webmagic-core</artifactId>
    <version>0.7.4</version>
</dependency>
<dependency>
    <groupId>us.codecraft</groupId>
    <artifactId>webmagic-extension</artifactId>
    <version>0.7.4</version>
</dependency>

WebMagic使用slf4j-log4j12作为slf4j的实现.如果你自己定制了slf4j的实现,请在项目中去掉此依赖。

<dependency>
    <groupId>us.codecraft</groupId>
    <artifactId>webmagic-extension</artifactId>
    <version>0.7.4</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
    </exclusions>
</dependency>

三. 爬取数据(springBoot+mybatis+webMagic)存入数据库

1. controller层代码如下,然后通过http://localhost:8090/robinBootApi/crawlData/crawlBookList  来发起数据爬取

package com.robinbootweb.dmo.controller;

import com.robinboot.facade.CrawlFacadeService;
import com.robinboot.query.CrawlQuery;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @auther: TF12778
 * @date: 2021/1/28 14:02
 * @description:
 */
@Controller
@RequestMapping(value = "/crawlData")
public class CrawlController {

    private static Log logger = LogFactory.getLog(CrawlController.class);

    @Autowired
    CrawlFacadeService webMagicFacadeService;

    /**
     *  @auther: TF12778
     *  @date:   2021/1/27 11:15
     *  @description: http://localhost:8090/robinBootApi/crawlData/crawlDoubanMoive
     *  请求豆瓣数据
     */
    @ResponseBody
    @RequestMapping(value = "/crawlDoubanMoive", method = RequestMethod.GET)
    public void crawlDoubanMoive(CrawlQuery query) {
        webMagicFacadeService.crawlDoubanMoive(query);
    }

    /**
     *  @auther: TF12778
     *  @date:   2021/1/27 11:15
     *  @description: http://localhost:8090/robinBootApi/crawlData/crawlBookList
     *  请求全部的列表数据
     */
    @ResponseBody
    @RequestMapping(value = "/crawlBookList", method = RequestMethod.GET)
    public void crawlBookList(CrawlQuery query) {
        webMagicFacadeService.crawlBookList(query);
    }

}

2. facade层发起真正的请求

这里通过page.addTargetRequests()方法来增加要抓取的URL,并通过page.putField()来保存抽取结果。page.getHtml().xpath()则是按照某个规则对结果进行抽取,这里抽取支持链式调用。调用结束后,toString()表示转化为单个String,all()则转化为一个String列表。

Spider是爬虫的入口类。Pipeline是结果输出和持久化的接口,这里bookListPipeline表示结果存到数据库。

package com.robinboot.service.facade.impl;

import com.robinboot.facade.CrawlFacadeService;
import com.robinboot.query.CrawlQuery;
import com.robinboot.service.WebMagic.Book.BookDetailPipeline;
import com.robinboot.service.WebMagic.Book.BookListPipeline;
import com.robinboot.service.WebMagic.Book.LittleBookDetailProcessor;
import com.robinboot.service.WebMagic.Book.LittleBookProcessor;
import com.robinboot.service.WebMagic.DoubanMoiveProcessor;
import com.robinboot.service.WebMagic.HttpClientDownloader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.Spider;

/**
 * @auther: TF12778
 * @date: 2021/1/28 13:44
 * @description:
 */
@Service("crawlFacadeService")
public class CrawlFacadeServiceImpl implements CrawlFacadeService {

    @Autowired
    BookListPipeline bookListPipeline;

    @Autowired
    BookDetailPipeline bookDetailPipeline;

    @Autowired
    LittleBookDetailProcessor littleBookDetailProcessor;

    @Override
    public void crawlDoubanMoive(CrawlQuery query) {
        Spider.create(new DoubanMoiveProcessor())
                .setDownloader(new HttpClientDownloader())
                .addUrl("https://www.douban.com/doulist/3907668/")
//                .addPipeline(new MySqlPipeline())
                .thread(5)
                .run();
    }

    /**
     *  @auther: TF12778
     *  @date:   2021/1/27 11:13
     *  @description: http://localhost:8090/robinBootApi/user/requestBookList
     */
    @Override
    public void crawlBookList(CrawlQuery query) {
        Spider.create(new LittleBookProcessor())
                .setDownloader(new HttpClientDownloader())
                .addUrl("http://deeee.cn:8080/tcshop/1111/catalog/toyy.html?orderBy=0")
                .addPipeline(this.bookListPipeline)  //这个this很关键,否则调dao层时,到接口不能自动被容器加载
                .thread(5)
                .run();
    }
}

 3.LittleBookProcessor爬虫处理类。爬虫主要的参数设置,以及url等在此设置

PageProcessor是webmagic-core的一部分,定制一个PageProcessor即可实现自己的爬虫逻辑。

package com.robinboot.service.WebMagic.Book;

import com.robinboot.service.WebMagic.HttpClientDownloader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import us.code
好的,下面我将为你展示如何实现一个基于Spring BootMybatis-Plus、Thymeleaf和Bootstrap的留言板。 1. 创建Spring Boot项目 首先,我们需要创建一个Spring Boot项目。你可以直接在IDE中创建,也可以使用Spring Boot CLI。这里我使用IDEA创建一个Maven项目。 2. 配置pom.xml 在pom.xml文件中添加以下依赖: ``` <dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- MyBatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.1.1</version> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> <!-- Bootstrap --> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>4.5.0</version> </dependency> <!-- Webjars Locator --> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator</artifactId> <version>0.40</version> </dependency> </dependencies> ``` 这里使用Spring Boot、Thymeleaf、Mybatis-Plus、MySQL Connector、Bootstrap以及Webjars Locator。 3. 配置数据库 我们需要在application.properties文件中配置数据库连接信息。 ``` spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` 这里使用MySQL作为数据库数据库名为test,用户名和密码均为root。 4. 创建留言实体类 我们需要创建一个留言实体类,用于映射数据库中的留言表。 ``` public class Message { private Long id; private String username; private String content; private Date createTime; // 省略getter和setter方法 } ``` 5. 创建Mapper 我们需要创建一个Mapper接口,用于操作留言表。 ``` @Mapper public interface MessageMapper extends BaseMapper<Message> { List<Message> selectAll(); } ``` 这里使用Mybatis-Plus提供的BaseMapper作为父接口,简化了Mapper的编写。 6. 创建Controller 我们需要创建一个Controller,用于处理请求。 ``` @Controller public class MessageController { @Autowired private MessageMapper messageMapper; @GetMapping("/") public String index(Model model) { List<Message> messages = messageMapper.selectAll(); model.addAttribute("messages", messages); return "index"; } @PostMapping("/") public String addMessage(Message message) { message.setCreateTime(new Date()); messageMapper.insert(message); return "redirect:/"; } } ``` 这里使用了@Autowired注解注入了MessageMapper。在index方法中,我们查询了所有留言,并将其存入Model中,然后返回index视图。在addMessage方法中,我们添加了一条留言,并重定向到首页。 7. 创建视图 我们需要创建一个视图,用于显示留言列表和添加留言。 ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:webjars="http://www.thymeleaf.org/extras/webjar"> <head> <title>留言板</title> <!-- Bootstrap --> <link rel="stylesheet" href="/webjars/bootstrap/4.5.0/css/bootstrap.min.css" /> </head> <body> <div class="container"> <h1>留言板</h1> <hr/> <form method="post"> <div class="form-group"> <label for="username">用户名:</label> <input type="text" class="form-control" id="username" name="username" required="required" /> </div> <div class="form-group"> <label for="content">留言内容:</label> <textarea class="form-control" id="content" name="content" required="required"></textarea> </div> <button type="submit" class="btn btn-primary">提交留言</button> </form> <hr/> <table class="table table-striped"> <thead> <tr> <th>用户名</th> <th>留言内容</th> <th>留言时间</th> </tr> </thead> <tbody> <tr th:each="message : ${messages}"> <td th:text="${message.username}"></td> <td th:text="${message.content}"></td> <td th:text="${#dates.format(message.createTime, 'yyyy-MM-dd HH:mm:ss')}"></td> </tr> </tbody> </table> </div> <!-- Bootstrap --> <script src="/webjars/bootstrap/4.5.0/js/bootstrap.min.js"></script> </body> </html> ``` 这里使用了Thymeleaf模板引擎,使用Bootstrap样式。在表格中,我们使用了th:each指令循环遍历留言列表,使用了#dates.format方法格式化留言时间。 8. 运行项目 现在,我们可以运行项目并访问http://localhost:8080来查看留言板了。 以上就是一个简单的Spring BootMybatis-Plus、Thymeleaf和Bootstrap留言板的实现过程。希望对你有帮助。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值