抓取网贷之家的数据爬虫

2023-12-19 10:20

本文主要是介绍抓取网贷之家的数据爬虫,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近在做ETL的项目,其中肯定要有数据,才能在各个工具之间抽取、转存、加载。按照天亮爬虫项目上的讲解,对网易之家的贷款机构进行了抓取。大致模块分为四部分:抓取模块、实体类、工具类、控制类。现在把相关的代码大致记录一遍,以防遗忘。

首先定义一个定义两个工具类,第一个工具类负责将将后期抓取的数据写入到一个文件里保存:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;/***文件读写类*/
public class IOUtil {public static void writeFile(String filePath, String value, String encoding) {FileOutputStream fos = null;try {fos = new FileOutputStream(new File(filePath));fos.write(value.getBytes(encoding));fos.close();} catch (Exception e) {e.printStackTrace();} finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}}public static void main(String[] args) {String filePath = "test.txt";String value = "中国人民万岁,hello world,123";String encoding = "utf-8";IOUtil.writeFile(filePath, value, encoding);System.out.println("done!");}
}
View Code

其次一个工具类是对抓取到的数据进行解析,因为后期抓取到的数据是json格式的,需要模板进行解析:

import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;/*** json解析工具类* */
public class JsonOperatorUtil {public static JSONObject toJSONObject(String str) {return (JSONObject) JSONValue.parse(str);}public static JSONArray toJSONArray(String str) {return (JSONArray) JSONValue.parse(str);}public static void main(String[] args) {String str = "[{\"one\":1,\"two\":\"2\"}]";
//        JSONObject jsonObject = JsonOperatorUtil.toJSONObject(str);JSONArray jsonObject = JsonOperatorUtil.toJSONArray(str);Iterator<JSONObject> iterator=jsonObject.iterator();while(iterator.hasNext()){System.out.println(iterator.next());}}
}
View Code

一个设置爬虫的层级类

/**设置任务的级别 */
public enum TaskLevel {HIGH, MIDDLE, LOW
}
View Code

接下来是一个爬虫实现接口类

public interface ICrawler {public CrawlResultPojo crawl(UrlPojo urlPojo);
}
View Code

在接口的实现上采取了两种实现方法,一种是利用HttpClient工具对数据抓取,另外一种直接用传统的HttpConnect来对数据进行抓取。

第一种方法的实现:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
public class HttpUrlConnectionCrawlerImpl implements ICrawler {@Overridepublic CrawlResultPojo crawl(UrlPojo urlPojo) {CrawlResultPojo crawlResultPojo = new CrawlResultPojo();if (urlPojo == null || urlPojo.getUrl() == null) {crawlResultPojo.setSuccess(false);crawlResultPojo.setPageContent(null);return crawlResultPojo;}StringBuilder stringBuilder = new StringBuilder();HttpURLConnection httpURLConnection = urlPojo.getConnection();if (httpURLConnection != null) {BufferedReader br = null;String line = null;try {br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"gb2312"));while ((line = br.readLine()) != null) {
//                    System.out.println(line);;stringBuilder.append(line+"\n");}crawlResultPojo.setSuccess(true);crawlResultPojo.setPageContent(stringBuilder.toString());} catch (Exception e) {e.printStackTrace();} finally {try {if (br != null) {br.close();}} catch (Exception e) {e.printStackTrace();System.out.println("done!");}}}return crawlResultPojo;}}
View Code

Httpclient实现类:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;import com.ztl.simple.iface.crawl.ICrawler;
import com.ztl.simple.pojos.CrawlResultPojo;
import com.ztl.simple.pojos.UrlPojo;public class HttpClientCrawlerImpl implements ICrawler {public CloseableHttpClient httpclient = HttpClients.custom().build();@Overridepublic CrawlResultPojo crawl(UrlPojo urlPojo) {if (urlPojo == null) {return null;}CrawlResultPojo crawlResultPojo = new CrawlResultPojo();CloseableHttpResponse response1 = null;BufferedReader br = null;try {HttpGet httpget = new HttpGet(urlPojo.getUrl());response1 = httpclient.execute(httpget);HttpEntity entity = response1.getEntity();InputStreamReader isr = new InputStreamReader(entity.getContent(),"utf-8");br = new BufferedReader(isr);String line = null;StringBuilder stringBuilder = new StringBuilder();while ((line = br.readLine()) != null) {stringBuilder.append(line + "\n");}crawlResultPojo.setSuccess(true);crawlResultPojo.setPageContent(stringBuilder.toString());return crawlResultPojo;} catch (Exception e) {e.printStackTrace();crawlResultPojo.setSuccess(false);} finally {if (response1 != null) {try {response1.close();} catch (IOException e1) {e1.printStackTrace();}}if (br != null) {try {br.close();} catch (IOException e1) {e1.printStackTrace();}}}return crawlResultPojo;}/*** 传入加入参数post参数的url pojo*/public CrawlResultPojo crawl4Post(UrlPojo urlPojo) {if (urlPojo == null) {return null;}CrawlResultPojo crawlResultPojo = new CrawlResultPojo();CloseableHttpResponse response1 = null;BufferedReader br = null;try {RequestBuilder rb = RequestBuilder.post().setUri(new URI(urlPojo.getUrl()));;// .addParameter("IDToken1",// "username").addParameter("IDToken2", "password").build();
Map<String, Object> parasMap = urlPojo.getParasMap();if (parasMap != null) {for (Entry<String, Object> entry : parasMap.entrySet()) {rb.addParameter(entry.getKey(), entry.getValue().toString());}}HttpUriRequest httpRequest = rb.build();response1 = httpclient.execute(httpRequest);HttpEntity entity = response1.getEntity();InputStreamReader isr = new InputStreamReader(entity.getContent(),"utf-8");br = new BufferedReader(isr);String line = null;StringBuilder stringBuilder = new StringBuilder();while ((line = br.readLine()) != null) {stringBuilder.append(line + "\n");}crawlResultPojo.setSuccess(true);crawlResultPojo.setPageContent(stringBuilder.toString());return crawlResultPojo;} catch (Exception e) {e.printStackTrace();crawlResultPojo.setSuccess(false);} finally {if (response1 != null) {try {response1.close();} catch (IOException e1) {e1.printStackTrace();}}if (br != null) {try {br.close();} catch (IOException e1) {e1.printStackTrace();}}}return crawlResultPojo;}public static void main(String[] args) throws Exception {HttpClientCrawlerImpl httpClientCrawlerImpl = new HttpClientCrawlerImpl();String url = "http://www.wangdaizhijia.com/front_select-plat";UrlPojo urlPojo = new UrlPojo(url);Map<String, Object> parasMap = new HashMap<String, Object>();int max_page_number = 1000;parasMap.put("currPage", 30);parasMap.put("params", "");parasMap.put("sort", 0);urlPojo.setParasMap(parasMap);CrawlResultPojo resultPojo = httpClientCrawlerImpl.crawl4Post(urlPojo);if (resultPojo != null) {System.out.println(resultPojo);}}
}
View Code

最后是抓取控制类:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;import org.json.simple.JSONArray;
import org.json.simple.JSONObject;import com.ztl.simple.impl.crawl.HttpClientCrawlerImpl;
import com.ztl.simple.pojos.CrawlResultPojo;
import com.ztl.simple.pojos.UrlPojo;
import com.ztl.simple.utils.IOUtil;
import com.ztl.simple.utils.JsonOperatorUtil;/*** 网易贷抓取管理器* * @author zel* */
public class WangYiDaiCrawlManager {public static HttpClientCrawlerImpl httpClientCrawlerImpl = new HttpClientCrawlerImpl();public static String[] column_key = { "platName", "locationAreaName","locationCityName", "platUrl" };public static int item_count = 0;private static CrawlResultPojo crawlOnePage(UrlPojo urlPojo) {CrawlResultPojo resultPojo = httpClientCrawlerImpl.crawl4Post(urlPojo);return resultPojo;}public static String parserOnePage(String jsonStr) {// 解析该jsonJSONObject jsonObj = JsonOperatorUtil.toJSONObject(jsonStr);JSONArray jsonArray = JsonOperatorUtil.toJSONArray(jsonObj.get("list").toString());StringBuilder stringBuilder = new StringBuilder();for (Object json : jsonArray) {JSONObject itemJson = (JSONObject) json;for (String column : column_key) {stringBuilder.append(itemJson.get(column) + "\t");}stringBuilder.append("\n");item_count++;}return stringBuilder.toString();}public static void processWangYiDai(String url, int max_page_number,String filePath) {// 存储所有的抓取条目StringBuilder all_items = new StringBuilder();UrlPojo urlPojo = new UrlPojo(url);Map<String, Object> parasMap = new HashMap<String, Object>();int have_download_page_count = 0;Set<String> uniqSet = new HashSet<String>();for (int pageNumber = 1; pageNumber <= max_page_number; pageNumber++) {parasMap.put("currPage", pageNumber);parasMap.put("params", "");parasMap.put("sort", 0);urlPojo.setParasMap(parasMap);CrawlResultPojo resultPojo = crawlOnePage(urlPojo);if (uniqSet.contains(resultPojo.getPageContent())) {System.out.println("碰到重复,代表已抓取完成!");break;} else {uniqSet.add(resultPojo.getPageContent());}if (resultPojo != null) {String content = resultPojo.getPageContent();String page_items = parserOnePage(content);all_items.append(page_items);have_download_page_count++;}}System.out.println("all items size---" + item_count);System.out.println("已经下载了---" + have_download_page_count);IOUtil.writeFile(filePath, all_items.toString(), "utf-8");System.out.println("save successfully~");}public static void main(String[] args) {String url = "http://www.wangdaizhijia.com/front_select-plat";int max_page_number = 1000;String fileName = "网易贷_数据集1.txt";processWangYiDai(url, max_page_number, fileName);System.out.println("done!");}
}
View Code

 

转载于:https://www.cnblogs.com/peizhe123/p/4661498.html

这篇关于抓取网贷之家的数据爬虫的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

MyBatis-plus处理存储json数据过程

《MyBatis-plus处理存储json数据过程》文章介绍MyBatis-Plus3.4.21处理对象与集合的差异:对象可用内置Handler配合autoResultMap,集合需自定义处理器继承F... 目录1、如果是对象2、如果需要转换的是List集合总结对象和集合分两种情况处理,目前我用的MP的版本

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映

C# LiteDB处理时间序列数据的高性能解决方案

《C#LiteDB处理时间序列数据的高性能解决方案》LiteDB作为.NET生态下的轻量级嵌入式NoSQL数据库,一直是时间序列处理的优选方案,本文将为大家大家简单介绍一下LiteDB处理时间序列数... 目录为什么选择LiteDB处理时间序列数据第一章:LiteDB时间序列数据模型设计1.1 核心设计原则

Java+AI驱动实现PDF文件数据提取与解析

《Java+AI驱动实现PDF文件数据提取与解析》本文将和大家分享一套基于AI的体检报告智能评估方案,详细介绍从PDF上传、内容提取到AI分析、数据存储的全流程自动化实现方法,感兴趣的可以了解下... 目录一、核心流程:从上传到评估的完整链路二、第一步:解析 PDF,提取体检报告内容1. 引入依赖2. 封装

MySQL中查询和展示LONGBLOB类型数据的技巧总结

《MySQL中查询和展示LONGBLOB类型数据的技巧总结》在MySQL中LONGBLOB是一种二进制大对象(BLOB)数据类型,用于存储大量的二进制数据,:本文主要介绍MySQL中查询和展示LO... 目录前言1. 查询 LONGBLOB 数据的大小2. 查询并展示 LONGBLOB 数据2.1 转换为十

使用SpringBoot+InfluxDB实现高效数据存储与查询

《使用SpringBoot+InfluxDB实现高效数据存储与查询》InfluxDB是一个开源的时间序列数据库,特别适合处理带有时间戳的监控数据、指标数据等,下面详细介绍如何在SpringBoot项目... 目录1、项目介绍2、 InfluxDB 介绍3、Spring Boot 配置 InfluxDB4、I

Java整合Protocol Buffers实现高效数据序列化实践

《Java整合ProtocolBuffers实现高效数据序列化实践》ProtocolBuffers是Google开发的一种语言中立、平台中立、可扩展的结构化数据序列化机制,类似于XML但更小、更快... 目录一、Protocol Buffers简介1.1 什么是Protocol Buffers1.2 Pro