人人贷散标爬虫实例

人人贷散标爬取实例

1.目标

对人人贷官网(https://www.renrendai.com/loan.html)的散标记录进行抓取,从中提取出借款人的信息,结果如下,运行结果

2.准备工作

使用的python库如下(python3):

#常规爬虫库
import requests
from bs4 import BeautifulSoup
import re
import json
import csv
#selenium登录
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#多进程
from multiprocessing import Process, Queue

import time

3.爬取实现

3.1main()

通过官网在散标列表中进入一个散标订单,其url为https://www.renrendai.com/loan-6782341.html,其中的6782341为散标订单的编号,其值改为多少就是订单编号为多少的散标记录。
使用多进程一次抓取10W数据,并使用列表生成式构造url.

3.1.1构造url

start_id 为起始订单id,若使用多进程,可以根据需要创建多个url_list
也可以使用生成器来构造url以减少内存占用

#
start_id = 1 #start_id为起始订单id
init_url = "https://www.renrendai.com/loan-{}.html"
url_list1 = [init_url.format(i + start_id + 00000) for i in range(25000)]

3.1.2启动读/写进程

当程序执行完,会输出everything is ok,please terminate提示程序执行完毕。
PS:若为多个子进程则可以用进程池Pool来写,就不用写成这样

    #2.父子进程就绪
    #2.1父进程创建Queue,并传给各个子进程:
    q = Queue()
    pw1 = Process(target=getHtmlText, args=(q, url_list1))

    pr = Process(target=parseAndSave, args=(q,))
    #2.2启动子进程pw*,pd,
    pw1.start()
    pr.start()
    #2.3等待pw结束即全部读取进程工作完毕,才强制中止pr进程
    pw1.join()
	print("******************everything is ok,please terminate ******************")

3.2 get_new_cookie()

本人在测试多次的情况下,session的cookie仍然会在二十分钟左右的时候过期,最后只能通过使用selenium来登录账号,并将登录后的cookie更新到session。
PS:浏览器驱动进程需使用quit()函数关闭,用close()会内存泄漏
关键代码实现如下:

def get_new_cookie(session):
		driver = webdriver.Chrome()
        cookies = driver.get_cookies()
        c = requests.cookies.RequestsCookieJar()
        for item in cookies:
            c.set(item["name"], item["value"])
        session.cookies.update(c)  # 登陆后刷新cookies
        driver.quit()

3.3 parseAndSave()

对页面进行解析,提取出部分信息

    while True:
        html_text_list = q.get(True)
        for index,html_text in enumerate(html_text_list):
            try:
            	#根据网页url进行常规解析/Beautiful的常规操作
                bs = BeautifulSoup(html_text, "html.parser")
                info = str(bs.find("script", {
    
    "src": "/ps/static/common/page/layout_c0258d7.js"}).next_sibling.string).replace("\n","")
                #根据正则表达式提取信息所在片段,并进行手动转码处理
                infoProcess = pattern.findall(info)[0].encode('utf-8').decode("utf-8").replace('\\u0022', '"').replace("\\u002D","-").replace("'","").replace("\\u005C","\\").replace(";","") #+ '"}}'
                info_dict = json.loads(infoProcess)
 
                #解析失败则跳过
                if "gender" not in info_dict["borrower"]:
                    print("gender not in borrower'key,index:",index)
                    continue
                    
                with open("all.csv","a") as csvfile:
                    writer = csv.writer((csvfile))
                    #具体写入数据可根据json进行取舍
                    writer.writerow(info_dict["loan"]["loanId"])
                print("id:{} has done".format(info_dict["loan"]["loanId"]))
                
            except Exception as e:
                print("Exception in parser:",info_dict["loan"]["loanId"])
                continue

3.4 getHtmlText()

getHtmlText()功能为读取数据的进程,即根据主函数提供的url进行请求,并定期重新登录更新cookies,该函数使用multiprocessing的Queue将返回的页面传给数据解析函数parseAndSave()。
主要代码片段如下:

    for index,url in enumerate(url_list):#len(url_list):
        try:
            res = session.get(url,timeout=10,headers=my_header)
            res.raise_for_status()
            res.encoding = res.apparent_encoding
            htmlTextList.append(res.text)
            print("request:"+str(index))
            if (index+1)%250 == 0:
                print(res.text)
                get_new_cookie(session)
            #网页文本列表满十个就向解析进程发送数据
            if (index+1)%10 == 0:
                q.put(htmlTextList)
                htmlTextList = []
        except Exception as e:
            print("Exception in request:",index)

4.最后

1.文章只给出部分关键代码/后续可能会将完整代码放至github
2.文章中使用requests为阻塞式访问,可以采用异步aiohttp库,一分钟可以爬取1200条散标记录。

猜你喜欢

转载自blog.csdn.net/zsllsz2022/article/details/104327748