Elasticsearch系列(十)----使用webmagic爬取数据导入到ES

2024-06-17 05:38

本文主要是介绍Elasticsearch系列(十)----使用webmagic爬取数据导入到ES,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

webmagic主要有两个文件




一个是对爬取页面进行处理,一个是对页面处理之后的数据进行保存:


CSDNPageProcessor

package com.fendo.webmagic;import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;import com.fendo.common.ClientFactory;
import com.fendo.common.CommonUtils;
import com.fendo.entity.CsdnBlog;import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.indices.CreateIndex;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;/*** CSDN页面爬取* @author fendo**/
//@RunWith(SpringJUnit4ClassRunner.class)
//@WebAppConfiguration
//@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class CSDNPageProcessor implements PageProcessor{@Autowiredprivate static JdbcPipeline jdbcPipeline;private static String username="u011781521";  // 设置csdn用户名  private static int size = 0;// 共抓取到的文章数量  private JestClient jestClient;// 抓取网站的相关配置,包括:编码、抓取间隔、重试次数等      private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setUserAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");@Overridepublic Site getSite() {return site;}@Overridepublic void process(Page page) {// 列表页  if (!page.getUrl().regex("http://blog\\.csdn\\.net/" + username + "/article/details/\\d+").match()) {  // 添加所有文章页  page.addTargetRequests(page.getHtml().xpath("//div[@id='article_list']").links()// 限定文章列表获取区域  .regex("/" + username + "/article/details/\\d+")  .replace("/" + username + "/", "http://blog.csdn.net/" + username + "/")// 巧用替换给把相对url转换成绝对url  .all());  // 添加其他列表页  page.addTargetRequests(page.getHtml().xpath("//div[@id='papelist']").links()// 限定其他列表页获取区域  .regex("/" + username + "/article/list/\\d+")  .replace("/" + username + "/", "http://blog.csdn.net/" + username + "/")// 巧用替换给把相对url转换成绝对url  .all());  // 文章页  } else {  size++;// 文章数量加1  page.putField("key", Integer.parseInt(page.getUrl().regex("http://blog\\.csdn\\.net/" + username + "/article/details/(\\d+)").get()));page.putField("title", CommonUtils.replaceHTML(page.getHtml().xpath("//div[@class='article_title']//span[@class='link_title']/a/text()").get()));page.putField("content",CommonUtils.replaceHTML(page.getHtml().xpath("//div[@class='article_content']/allText()").get()));page.putField("dates",page.getHtml().xpath("//div[@class='article_r']/span[@class='link_postdate']/text()").get());System.out.println("+++++++++++++++date:"+page.getHtml().xpath("//div[@class='article_r']/span[@class='link_postdate']/text()").get());page.putField("tags",CommonUtils.replaceHTML(listToString(page.getHtml().xpath("//div[@class='article_l']/span[@class='link_categories']/a/allText()").all())));page.putField("category",CommonUtils.replaceHTML(listToString(page.getHtml().xpath("//div[@class='category_r']/label/span/text()").all())));page.putField("view", Integer.parseInt(page.getHtml().xpath("//div[@class='article_r']/span[@class='link_view']").regex("(\\d+)人阅读").get()));page.putField("comments",Integer.parseInt(page.getHtml().xpath("//div[@class='article_r']/span[@class='link_comments']").regex("\\((\\d+)\\)").get()));page.putField("copyright",page.getHtml().regex("bog_copyright").match() ? 1 : 0);page.putField("url", page.getUrl().get());//创建索引ObjectMapper mapper = new ObjectMapper();//创建clientTransportClient client;CsdnBlog csdnBlog = new CsdnBlog();csdnBlog.setId(size);csdnBlog.setTags((String)page.getResultItems().get("tags"));csdnBlog.setKeyes((Integer)page.getResultItems().get("key"));csdnBlog.setTitles((String)page.getResultItems().get("title"));csdnBlog.setDates((String)page.getResultItems().get("dates"));csdnBlog.setCategory((String)page.getResultItems().get("category"));csdnBlog.setViews((Integer)page.getResultItems().get("view"));csdnBlog.setComments((Integer)page.getResultItems().get("comments"));csdnBlog.setCopyright((Integer)page.getResultItems().get("copyright"));csdnBlog.setContent((String)page.getResultItems().get("content"));try {//设置集群名称Settings settings = Settings.builder().put("cluster.name", "my-application").build();// 集群名client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));IndexResponse response = client.prepareIndex("csdnblog", "article").setSource(mapper.writeValueAsString(csdnBlog)).execute().actionGet();System.out.println(response.toString());} catch (Exception e) {e.printStackTrace();}// 把对象输出控制台  //System.out.println("获取的数据:"+page.toString()); }  }// 把list转换为string,用,分割  public static String listToString(List<String> stringList) {  if (stringList == null) {  return null;  }  StringBuilder result = new StringBuilder();  boolean flag = false;  for (String string : stringList) {  if (flag) {  result.append(",");  } else {  flag = true;  }  result.append(string);  }  return result.toString();  }  public static void main(String[] args) {  long startTime, endTime;  System.out.println("【爬虫开始】...");  startTime = System.currentTimeMillis();  //ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");ApplicationContext applicationContext = new FileSystemXmlApplicationContext(  "classpath:applicationContext.xml");  JdbcPipeline jdbcPipeline=(JdbcPipeline)applicationContext.getBean("jdbcPipeline");System.out.println(jdbcPipeline.toString());Spider.create(new CSDNPageProcessor()).addUrl("http://blog.csdn.net/u011781521/article/list/1")//.addUrl("http://blog.csdn.net/u011781521/article/list/1").addPipeline(jdbcPipeline).thread(5).run();// 从用户博客首页开始抓,开启5个线程,启动爬虫  // Spider.create(new CsdnBlogPageProcessor()).addUrl("http://blog.csdn.net/" + username).thread(5).run();  endTime = System.currentTimeMillis();  System.out.println("【爬虫结束】共抓取" + size + "篇文章,耗时约" + ((endTime - startTime) / 1000) + "秒,已保存到数据库,请查收!");  }  
}


注意:


在上面的代码中,不但通过jdbcPipeline保存了数据,还通过TransportClient 往ES中保存了数据!!


JdbcPipeline

package com.fendo.webmagic;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;import com.fendo.entity.CsdnBlog;
import com.fendo.mapper.CsdnBlogMapper;import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;@Component("jdbcPipeline")
public class JdbcPipeline implements Pipeline{@AutowiredCsdnBlogMapper csdnBlogMapper;@Overridepublic void process(ResultItems resultItems, Task task) {Map<String,Object> items = resultItems.getAll();if(resultItems!=null&&resultItems.getAll().size()>0){CsdnBlog csdnBlog = new CsdnBlog();csdnBlog.setTags((String)items.get("tags"));csdnBlog.setKeyes((Integer)items.get("key"));csdnBlog.setTitles((String)items.get("title"));csdnBlog.setDates((String)items.get("dates"));csdnBlog.setCategory((String)items.get("category"));csdnBlog.setViews((Integer)items.get("view"));csdnBlog.setComments((Integer)items.get("comments"));csdnBlog.setCopyright((Integer)items.get("copyright"));csdnBlog.setContent((String)items.get("content"));System.out.println("-----------------------------------------------------------------------process:"+csdnBlog.toString());csdnBlogMapper.insert(csdnBlog);}}}


对应的数据库脚本:

CREATE TABLE `csdnblog` (`id` int(11) unsigned NOT NULL AUTO_INCREMENT,`keyes` int(11) unsigned NOT NULL,`titles` varchar(255) NOT NULL,`content` varchar(10240) NOT NULL,`dates` varchar(255) DEFAULT NULL,`tags` varchar(255) DEFAULT NULL,`category` varchar(255) DEFAULT NULL,`views` int(11) unsigned DEFAULT NULL,`comments` int(11) unsigned DEFAULT NULL,`copyright` int(20) unsigned DEFAULT NULL,`url` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3301 DEFAULT CHARSET=utf8;

完整项目: http://download.csdn.net/download/u011781521/9966717

这篇关于Elasticsearch系列(十)----使用webmagic爬取数据导入到ES的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1068606

相关文章

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.