webmagic使用

news/2024/7/19 11:16:28 标签: 数据库, java, 爬虫

webmagic是Java语言用于爬虫的工具。官网地址:http://webmagic.io/,中文文档地址:http://webmagic.io/docs/zh/

使用webmagic有3种配置需要注意,日志配置(log4j),webmagic爬取配置(如超时时间),使用数据库的话数据库连接池配置。有一些配置最好做到可以随机器性能情况而改变配置信息。这样做的目的是为了将项目打成包以后在命令行下执行程序可以随时更改配置。因此有些配置文件就不像c3p0配置文件一样放在源码文件夹下,而是相对与项目路径来说。

webmagic的架构图如下:

                                               

  从该架构图上可以得到一个信息,对于每一个页面来说,都会经历一个完成的过程,即从downloader--->pipeline,如列表页也会进入pipeline,所以列表页虽然没有数据需要存储,但在pipeline中去拿值就会出现空指针,因此在pipeline中要先进行判断,有值的情况下在进行数据库存储操作。

  在页面解析部分(待补充),webmagic将解析语法做了一些改变,

    1、如将正则表达式中.用\.表示

    2、*变成了.*,直接使用表示通配符

    3、xpath语法也进行了扩充。

代码示例:

  webmagic版本:0.6.0

package com.lh.pipeline;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

public class MysqlPipeline implements Pipeline {
    //有一个容器
    static DataSource ds = new ComboPooledDataSource();//直接使用即可,不用显示的配置,其会自动识别配置文件
    public void process(ResultItems resultItems, Task task) {
        //每进来一次代表一条记录
        //如果容器值达到1000,存一次数据库并将数据清空,否则将数据存入容器
        Map<String, Object> m = resultItems.getAll();
        if(!m.isEmpty()){
        Set<Entry<String, Object>> set = m.entrySet();
        Iterator<Entry<String, Object>> reconds = set.iterator();
        String url = null;
        String name = null;
        String content = null;
        for(int i=0;i<set.size();i++){
            Entry<String, Object> recond =reconds.next();
            if(i==0){
                url = recond.getValue().toString();
            }else if(i==1){
                name = recond.getValue().toString();
            }else if(i==2){
                content = recond.getValue().toString();
            }
            
        }
        
        Connection conn = null;
        try {
            conn = ds.getConnection();
            String sql = "insert into softList(url,name,content) values(?,?,?)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, url);
            pstmt.setString(2, name);
            pstmt.setString(3, content);
            pstmt.execute();
            pstmt.close();
            conn.close();
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
    }
    }
}
package com.lh.spider;

import com.lh.pipeline.MysqlPipeline;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.FilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;

public class ProgramSpider implements PageProcessor {
    
    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000);
    
    public static final String URL_LIST = "http://www\\.xiazaiba\\.com/downlist/187_\\d{1,4}\\.html";

    public static final String URL_POST = "http://www\\.xiazaiba\\.com/html/\\d+.html";
    
    public void process(Page page) {
        
        if(page.getUrl().regex("http://www\\.xiazaiba\\.com/downlist/187\\.html").match()||page.getUrl().regex(URL_LIST).match()){
            //第一页
            //加入详情页
            //加入列表页
            page.addTargetRequests(page.getHtml().xpath("//ul[@class='cur-cat-list']/li/a[1]").links().all());
            page.addTargetRequests(page.getHtml().xpath("//div[@class='ylmf-page']").links().all());
        }else{
            //详情页
            page.putField("url", page.getUrl());
            page.putField("ProgramName", page.getHtml().xpath("//div[@class='soft-title']/html()"));
            page.putField("ProgramContent", page.getHtml().xpath("//td[@class='soft-content']/html()"));
        }
    }

    public Site getSite() {
        return site;
    }
    public static void main(String[] args) {
        Spider.create(new ProgramSpider())
        .addUrl("http://www.xiazaiba.com/downlist/187.html") 
        .addPipeline(new MysqlPipeline()).thread(10)
        .run();
    }
}

 

转载于:https://www.cnblogs.com/duex/p/6380432.html


http://www.niftyadmin.cn/n/598862.html

相关文章

对Mybatis的初步认识

1、认识Mybatis MyBatis 是支持普通 SQL 查询&#xff0c;存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索。 MyBatis 可以使用简单的XML 或注解用于配置和原始映射&#xff0c;将接口和 Java 的 POJO&#xff08…

Java分布式 一些概念理解

转至 java那些事 2017-02-09 有些朋友工作一年了觉得该深入一下子了&#xff0c;所以想深入学习一下以提升自己的专业技能&#xff0c;想问一下如何入门Java分布式应用&#xff0c;学习过程大致是怎么样的&#xff0c;涉及到那些知识&#xff0c;框架呢&#xff1f;有那些资料可…

Redis 实例排除步骤

Redis 应用案例 - 在问题中不断成长原创 2017-02-05 杜亦舒 本文翻译整理自 Andy Grunwald 发布的一篇文章&#xff0c;写的是作者所在公司使用 Redis 时遇到的问题&#xff0c;以及处理过程&#xff0c;在不断解决调整中积累了很多 Redis 的使用经验背景产品类型&#xff1a;酒…

调试SharePoint web part时, 如何可以多个人同时启动调试?

<iframe align"top" marginwidth"0" marginheight"0" src"http://www.zealware.com/46860.html" frameborder"0" width"468" scrolling"no" height"60"></iframe>By Ben如果同时…

nginx启动脚本

nginx启动脚本如下:&#xff08;本文永久地址&#xff1a;http://woymk.blog.51cto.com/10000269/1896533&#xff09;#!/bin/sh # # nginx - this script starts and stops the nginx daemon # # chkconfig: - 85 15 # description: Nginx is an HTTP(S) server, HTTP(S) r…

Quartz.net官方开发指南 第十二课:Quartz 的其他特性

Plug-Ins 插件 Quartz提供了一个接口(ISchedulerPlugin)来插入附加的功能。 随Quartz打包儿来的插件有很多有用的功能&#xff0c;它们在Quartz.Plugins命名空间中找到。他们提供了诸如自动安排任务的日程&#xff0c;将任务和触发器事件的历史记入日志以及虚拟机退出时确保干净…

机器学习之深入理解SVM

在浏览本篇博客之前&#xff0c;最好先查看一下我写的另一篇文章机器学习之初识SVM&#xff08;点击可查阅哦&#xff09;&#xff0c;这样可以更好地为了结以下内容做铺垫&#xff01; 支持向量机学习方法包括构建由简至繁的模型&#xff1a;线性可分支持向量机、线性支持向量…

List添加Item时, 如何去判断某个字段, 并且保证字段数据不重复性

<iframe align"top" marginwidth"0" marginheight"0" src"http://www.zealware.com/46860.html" frameborder"0" width"468" scrolling"no" height"60"></iframe>来自与微软专家…