抓取网贷之家的数据爬虫

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

相关文章

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

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

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

使用SpringBoot整合Sharding Sphere实现数据脱敏的示例

《使用SpringBoot整合ShardingSphere实现数据脱敏的示例》ApacheShardingSphere数据脱敏模块,通过SQL拦截与改写实现敏感信息加密存储,解决手动处理繁琐及系统改... 目录痛点一:痛点二:脱敏配置Quick Start——Spring 显示配置:1.引入依赖2.创建脱敏

详解如何使用Python构建从数据到文档的自动化工作流

《详解如何使用Python构建从数据到文档的自动化工作流》这篇文章将通过真实工作场景拆解,为大家展示如何用Python构建自动化工作流,让工具代替人力完成这些数字苦力活,感兴趣的小伙伴可以跟随小编一起... 目录一、Excel处理:从数据搬运工到智能分析师二、PDF处理:文档工厂的智能生产线三、邮件自动化:

Python数据分析与可视化的全面指南(从数据清洗到图表呈现)

《Python数据分析与可视化的全面指南(从数据清洗到图表呈现)》Python是数据分析与可视化领域中最受欢迎的编程语言之一,凭借其丰富的库和工具,Python能够帮助我们快速处理、分析数据并生成高质... 目录一、数据采集与初步探索二、数据清洗的七种武器1. 缺失值处理策略2. 异常值检测与修正3. 数据

pandas实现数据concat拼接的示例代码

《pandas实现数据concat拼接的示例代码》pandas.concat用于合并DataFrame或Series,本文主要介绍了pandas实现数据concat拼接的示例代码,具有一定的参考价值,... 目录语法示例:使用pandas.concat合并数据默认的concat:参数axis=0,join=

C#代码实现解析WTGPS和BD数据

《C#代码实现解析WTGPS和BD数据》在现代的导航与定位应用中,准确解析GPS和北斗(BD)等卫星定位数据至关重要,本文将使用C#语言实现解析WTGPS和BD数据,需要的可以了解下... 目录一、代码结构概览1. 核心解析方法2. 位置信息解析3. 经纬度转换方法4. 日期和时间戳解析5. 辅助方法二、L

使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)

《使用Python和Matplotlib实现可视化字体轮廓(从路径数据到矢量图形)》字体设计和矢量图形处理是编程中一个有趣且实用的领域,通过Python的matplotlib库,我们可以轻松将字体轮廓... 目录背景知识字体轮廓的表示实现步骤1. 安装依赖库2. 准备数据3. 解析路径指令4. 绘制图形关键

解决mysql插入数据锁等待超时报错:Lock wait timeout exceeded;try restarting transaction

《解决mysql插入数据锁等待超时报错:Lockwaittimeoutexceeded;tryrestartingtransaction》:本文主要介绍解决mysql插入数据锁等待超时报... 目录报错信息解决办法1、数据库中执行如下sql2、再到 INNODB_TRX 事务表中查看总结报错信息Lock

使用C#删除Excel表格中的重复行数据的代码详解

《使用C#删除Excel表格中的重复行数据的代码详解》重复行是指在Excel表格中完全相同的多行数据,删除这些重复行至关重要,因为它们不仅会干扰数据分析,还可能导致错误的决策和结论,所以本文给大家介绍... 目录简介使用工具C# 删除Excel工作表中的重复行语法工作原理实现代码C# 删除指定Excel单元