spring 整合 mybatis+webmagic爬取数据并持久化

因为最近在爬数据进行分析,数据已经爬好了,但最后还是需要持久化到数据库。因为公司用的持久化框架是mybatis,这里面又不需要mvc的架构,所以只需要spring 和 mybatis进行整合就行了,spring 作为bean容器,mybatis负责orm映射和持久化。

我这边用的是gradle构建工具,下面是我的依赖:

    compile 'us.codecraft:webmagic-core:0.5.3'
    compile('us.codecraft:webmagic-extension:0.5.3')
    compile 'org.seleniumhq.selenium:selenium-java:2.8.0'
    compile group: 'us.codecraft', name: 'webmagic-selenium', version: '0.5.2'
    compile 'com.github.detro:phantomjsdriver:1.2.0'
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.5'
    compile 'org.springframework:spring-aop:4.2.4.RELEA SE'
    compile 'org.springframework:spring-context:4.2.4.RELEASE'
    compile 'org.springframework:spring-beans:4.2.4.RELEASE'
    compile 'org.springframework:spring-web:4.2.4.RELEASE'
    compile 'org.springframework:spring-webmvc:4.2.4.RELEASE'
    compile 'org.springframework:spring-tx:4.2.4.RELEASE'
    compile 'org.springframework:spring-jdbc:4.2.4.RELEASE'
    compile 'org.springframework:spring-test:4.2.4.RELEASE'
    compile 'mysql:mysql-connector-java:5.1.38'
    compile 'org.mybatis.generator:mybatis-generator-core:1.3.2'
    compile 'org.mybatis:mybatis-spring:1.2.3'
    compile 'org.mybatis:mybatis:3.3.0'
    compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.6.2'
    compile group: 'org.apache.commons', name: 'commons-dbcp2', version: '2.1.1'
    compile group: 'org.projectlombok', name: 'lombok', version: '1.16.10'

接下来是实体类PO(基金):

@Data
@Builder
public class Fund{
    private int id;
    private String fundCode;
    private String fundName;
    private String dailyGrowthRate;
    private String monthlyGrowthRate;
}

数据库的schema如下:

CREATE TABLE `fund` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fund_code` varchar(255) DEFAULT NULL,
  `fund_name` varchar(255) DEFAULT NULL,
  `daily_growth_rate` varchar(255) DEFAULT NULL,
  `monthly_growth_rate` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11594 DEFAULT CHARSET=utf8;


然后是UserMapper:

public interface FundMapper {
    int insert(Fund fund);
}

然后是业务类UserService:
其中@Service注解配合ComponentScan会把这个类注入Spring容器
@Autowired 是按照类型进行装配

@Service
public class FundService {

    @Autowired
    private FundMapper mapper;

    public int insert(Fund fund){
        return mapper.insert(fund);
    }

}

接下来是UserMapper.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="stock.mapper.FundMapper">

    <resultMap id="BaseResultMap" type="stock.po.Fund">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="fund_code" property="fundCode" jdbcType="VARCHAR"/>
        <result column="fund_name" property="fundName" jdbcType="VARCHAR"/>
        <result column="daily_growth_rate" property="dailyGrowthRate" jdbcType="VARCHAR"/>
        <result column="monthly_growth_rate" property="monthlyGrowthRate" jdbcType="VARCHAR"/>
    </resultMap>

    <sql id="BaseColumnList">
        id,fund_code,fund_name,daily_growth_rate,monthly_growth_rate
    </sql>

    <insert id="insert" parameterType="stock.po.Fund">
        INSERT INTO fund(
        <include refid="BaseColumnList"/>
        )
        VALUES (
        #{id,jdbcType=INTEGER},
        #{fundCode,jdbcType=VARCHAR},
        #{fundName,jdbcType=VARCHAR},
        #{dailyGrowthRate,jdbcType=VARCHAR},
        #{monthlyGrowthRate,jdbcType=VARCHAR}
        )
    </insert>

</mapper>

接着是mybatis的配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <mappers>
        <mapper resource="mapper/FundMapper.xml"/>
    </mappers>

</configuration>

然后就是spring的配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <context:component-scan base-package="stock.**"/>

    <!-- 数据源,使用dbcp -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" /><!-- 这里的name不能直接使用driver,必须是driverClassName -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- sqlSessionFactory -->
    <bean id = "sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加载mybatis的配置文件 -->
        <property name="configLocation" value="mybatis-config.xml"></property>
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- mapper配置,MapperFactoryBean可以根据mapper接口来生成代理对象 -->
    <bean id="fundMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="stock.mapper.FundMapper"/>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>


</beans>

其中jdbc.properties的文件如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=

然后逻辑代码如下:

public class NewFundProcessor implements PageProcessor {

    private Logger log = LoggerFactory.getLogger(NewFundProcessor.class);

    private ApplicationContext context;

    public NewFundProcessor() {
        context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }

    private FundService fundService;

    private static final String prefix = "https://e.lufunds.com/jijin/allFund?subType=&haitongGrade=&fundGroupId=&currentPage=";
    private static final String suffix = "&orderType=twelve_month_increase_desc&canFixInvest=&searchWord=#sortTab";
    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(3000)
            .setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36");


    @Override
    public void process(Page page) {
        System.out.println("first ------------------");
        List<String> list = page.getHtml().xpath("div[@class='listTable']/table[@id='fundTable']/tbody/tr").all();

        for (int i = 0; i < list.size(); i++) {

            Html h = new Html(list.get(i).replace("td", "div"));
            String fundCode = h.xpath("//div[1]/text()").get();
            String fundName = h.xpath("//div[2]/a/text()").get();
            String dailyGrowthRate = h.xpath("//div[4]/span/text()").get();
            String monthGrowthRate = h.xpath("//div[5]/span/text()").get();
            String startAmount = h.xpath("//div[10]/text()").get();
            System.out.println("基金代码:" + h.xpath("//div[1]/text()"));
            System.out.println("基金简介:" + h.xpath("//div[2]/a/text()"));
            System.out.println("最新净值:" + h.xpath("//div[3]/p[1]/text()"));
            System.out.println("时间:" + h.xpath("//p[2]/text()"));
            System.out.println("日增长率:" + h.xpath("//div[4]/span/text()"));
            System.out.println("最近一月增长率:" + h.xpath("//div[5]/span/text()"));
            System.out.println("最近三月增长率:" + h.xpath("//div[6]/span/text()"));
            System.out.println("最近一年增长率:" + h.xpath("//div[7]/span/text()"));
            System.out.println("今年增长率:" + h.xpath("//div[8]/span/text()"));
            System.out.println("成立以来增长率:" + h.xpath("//div[9]/span/text()"));
            System.out.println("起投金额:" + h.xpath("//div[10]/text()"));
            fundService = (FundService) context.getBean("fundService");
            Fund fund = new Fund();
            fund.setFundCode(fundCode);
            fund.setFundName(fundName);
            fund.setDailyGrowthRate(dailyGrowthRate);
            fund.setMonthlyGrowthRate(monthGrowthRate);
            int result = fundService.insert(fund);
            System.out.println(result);

            System.out.println("-------");

        }

        System.out.println("size:" + list.size());


    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {

        List<String> urls = new ArrayList<String>();
        for (int i = 1; i <= 250; i++) {
            String url = prefix+i+suffix;
            urls.add(url);
        }

        NewFundProcessor processor = new NewFundProcessor();
            Spider.create(processor)
                    .startUrls(urls)
                    .thread(10)
                    .runAsync();

    }
}

执行之后会往数据库插入3000多条基金的数据:

7.png
8.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,359评论 6 343
  • 摘要: 基本概念 1.1、Spring spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的...
    ITsupuerlady阅读 1,357评论 0 8
  • 青春是一道明媚的忧伤,我没哭,可是眼泪流下来了。我不喜欢这样的青春太过于伤感,可是却无法逃脱这样的情感,不得不...
    迟皖阅读 353评论 0 1
  • 早,油饼,泡面 午,西红柿鸡蛋面 晚,地瓜,韭菜火烧 差点忘了,晚安
    你三大爷的舅姥爷阅读 97评论 0 0