洛谷用户爬虫
截至目前,洛谷已经有了40余万名用户,本代码爬取了一些样本,以供后续(可能)的数据分析。
改动之处
- 在 URL 后面加
?_contentOnly=1
即可直接获取 JSON 格式的信息,无需再使用正则匹配,加快速度 - 修掉了几个出锅的地方
成品代码
您可以在 GitHub 上查看到该文件的最新更新。
import json
import time
import pymongo
import requests
dbclient = pymongo.MongoClient("mongodb://127.0.0.1:27017/")
luogudb = dbclient["luogu"]
dbcol = luogudb["user"]
headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4331.0 Safari/537.36", }
def getUser(uid):
url = f"https://www.luogu.com.cn/user/{uid}?_contentOnly=1"
redata = requests.get(url, headers=headers).text
return json.loads(redata)
for uid in range(1, 2):
if list(dbcol.find({'uid': uid})) == []:
tmpdict = {}
tmpdict["_id"] = uid
tmpdict["uid"] = uid
tmpdata = getUser(uid)
if tmpdata["code"] == 200:
tmpdict["data"] = tmpdata["currentData"]["user"]
dbcol.insert_one(tmpdict)
print(f"Successfully get user {uid}.")
time.sleep(0.5)
else:
print(f"Fail to get user {uid}.")
time.sleep(0.5)
else:
print(f"User {uid} is already exists.")