連連一括入札のクローリング例
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.1メイン()
公式ウェブサイトからルース入札リストにルース入札注文を入力します。その 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 読み取り/書き込みプロセスの開始
プログラムを実行すると、「すべてが正常です。終了してください」というメッセージが表示され、プログラムが実行されたことを確認するメッセージが表示されます。
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()
何度テストしても、セッション Cookie は 20 分程度で期限切れになってしまいますが、結局、Selenium を使用してアカウントにログインし、セッションにログインした後に Cookie を更新することしかできませんでした。
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() の関数は、データを読み取るプロセスです。つまり、main 関数によって提供された URL に従ってリクエストを作成し、定期的に再ログインして Cookie を更新します。この関数は、マルチプロセッシング キューを使用して、返されたページをデータ解析関数 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. 記事で使用されているリクエストはアクセスをブロックしており、非同期 aiohttp ライブラリを使用すると、1 分間に 1200 件の散在レコードをクロールできます。