抓取网贷之家的数据爬虫

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多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

解决pandas无法读取csv文件数据的问题

《解决pandas无法读取csv文件数据的问题》本文讲述作者用Pandas读取CSV文件时因参数设置不当导致数据错位,通过调整delimiter和on_bad_lines参数最终解决问题,并强调正确参... 目录一、前言二、问题复现1. 问题2. 通过 on_bad_lines=‘warn’ 跳过异常数据3

C#监听txt文档获取新数据方式

《C#监听txt文档获取新数据方式》文章介绍通过监听txt文件获取最新数据,并实现开机自启动、禁用窗口关闭按钮、阻止Ctrl+C中断及防止程序退出等功能,代码整合于主函数中,供参考学习... 目录前言一、监听txt文档增加数据二、其他功能1. 设置开机自启动2. 禁止控制台窗口关闭按钮3. 阻止Ctrl +

java如何实现高并发场景下三级缓存的数据一致性

《java如何实现高并发场景下三级缓存的数据一致性》这篇文章主要为大家详细介绍了java如何实现高并发场景下三级缓存的数据一致性,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 下面代码是一个使用Java和Redisson实现的三级缓存服务,主要功能包括:1.缓存结构:本地缓存:使

在MySQL中实现冷热数据分离的方法及使用场景底层原理解析

《在MySQL中实现冷热数据分离的方法及使用场景底层原理解析》MySQL冷热数据分离通过分表/分区策略、数据归档和索引优化,将频繁访问的热数据与冷数据分开存储,提升查询效率并降低存储成本,适用于高并发... 目录实现冷热数据分离1. 分表策略2. 使用分区表3. 数据归档与迁移在mysql中实现冷热数据分

C#解析JSON数据全攻略指南

《C#解析JSON数据全攻略指南》这篇文章主要为大家详细介绍了使用C#解析JSON数据全攻略指南,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、为什么jsON是C#开发必修课?二、四步搞定网络JSON数据1. 获取数据 - HttpClient最佳实践2. 动态解析 - 快速

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口

SQL中如何添加数据(常见方法及示例)

《SQL中如何添加数据(常见方法及示例)》SQL全称为StructuredQueryLanguage,是一种用于管理关系数据库的标准编程语言,下面给大家介绍SQL中如何添加数据,感兴趣的朋友一起看看吧... 目录在mysql中,有多种方法可以添加数据。以下是一些常见的方法及其示例。1. 使用INSERT I

Python使用vllm处理多模态数据的预处理技巧

《Python使用vllm处理多模态数据的预处理技巧》本文深入探讨了在Python环境下使用vLLM处理多模态数据的预处理技巧,我们将从基础概念出发,详细讲解文本、图像、音频等多模态数据的预处理方法,... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

MySQL 删除数据详解(最新整理)

《MySQL删除数据详解(最新整理)》:本文主要介绍MySQL删除数据的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、前言二、mysql 中的三种删除方式1.DELETE语句✅ 基本语法: 示例:2.TRUNCATE语句✅ 基本语