抓取网贷之家的数据爬虫

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

相关文章

Linux下利用select实现串口数据读取过程

《Linux下利用select实现串口数据读取过程》文章介绍Linux中使用select、poll或epoll实现串口数据读取,通过I/O多路复用机制在数据到达时触发读取,避免持续轮询,示例代码展示设... 目录示例代码(使用select实现)代码解释总结在 linux 系统里,我们可以借助 select、

Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题

《Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题》在爬虫工程里,“HTTPS”是绕不开的话题,HTTPS为传输加密提供保护,同时也给爬虫带来证书校验、... 目录一、核心问题与优先级检查(先问三件事)二、基础示例:requests 与证书处理三、高并发选型:

Python屏幕抓取和录制的详细代码示例

《Python屏幕抓取和录制的详细代码示例》随着现代计算机性能的提高和网络速度的加快,越来越多的用户需要对他们的屏幕进行录制,:本文主要介绍Python屏幕抓取和录制的相关资料,需要的朋友可以参考... 目录一、常用 python 屏幕抓取库二、pyautogui 截屏示例三、mss 高性能截图四、Pill

C#使用iText获取PDF的trailer数据的代码示例

《C#使用iText获取PDF的trailer数据的代码示例》开发程序debug的时候,看到了PDF有个trailer数据,挺有意思,于是考虑用代码把它读出来,那么就用到我们常用的iText框架了,所... 目录引言iText 核心概念C# 代码示例步骤 1: 确保已安装 iText步骤 2: C# 代码程

Pandas处理缺失数据的方式汇总

《Pandas处理缺失数据的方式汇总》许多教程中的数据与现实世界中的数据有很大不同,现实世界中的数据很少是干净且同质的,本文我们将讨论处理缺失数据的一些常规注意事项,了解Pandas如何表示缺失数据,... 目录缺失数据约定的权衡Pandas 中的缺失数据None 作为哨兵值NaN:缺失的数值数据Panda

C++中处理文本数据char与string的终极对比指南

《C++中处理文本数据char与string的终极对比指南》在C++编程中char和string是两种用于处理字符数据的类型,但它们在使用方式和功能上有显著的不同,:本文主要介绍C++中处理文本数... 目录1. 基本定义与本质2. 内存管理3. 操作与功能4. 性能特点5. 使用场景6. 相互转换核心区别

python库pydantic数据验证和设置管理库的用途

《python库pydantic数据验证和设置管理库的用途》pydantic是一个用于数据验证和设置管理的Python库,它主要利用Python类型注解来定义数据模型的结构和验证规则,本文给大家介绍p... 目录主要特点和用途:Field数值验证参数总结pydantic 是一个让你能够 confidentl

JAVA实现亿级千万级数据顺序导出的示例代码

《JAVA实现亿级千万级数据顺序导出的示例代码》本文主要介绍了JAVA实现亿级千万级数据顺序导出的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 前提:主要考虑控制内存占用空间,避免出现同时导出,导致主程序OOM问题。实现思路:A.启用线程池

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

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

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

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