python获取编程猫用户名

发布于 2024-07-10  103 次阅读


AI 摘要

```markdown **Excerpt:** The main purpose of this program is to retrieve user nicknames from the Codemao platform and save them to a file. Here is a detailed explanation of the program: **Import necessary modules:** - The `requests` module is used for sending HTTP requests. - The `json` module is used for handling JSON data. - The `threading` module is used for implementing multithreading. **Initialize variables:** - `namelist` is an empty list used to store retrieved user nicknames. **Define function `get_nickname`:** - This function takes a user ID as a parameter. - It sends an HTTP GET request to Codemao's user center honor API to fetch user information. - It parses the returned JSON data into a Python dictionary using `json.loads`. - It extracts the user nickname from the dictionary and adds it to the `namelist` list. - It prints the user nickname and user ID. - If an exception occurs (e.g., user does not exist), it catches the exception and continues. **Multithreading processing:** - Initialize the user ID `i` to 10000. - Contin

源代码

requirements

requests
json
threading

main.py

from requests import get
from json import loads,dumps
import threading

namelist = []

def get_nickname(user_id):
    try:
        nickname = loads(get(f'https://api.codemao.cn/creation-tools/v1/user/center/honor?user_id={user_id}').text)['nickname']
        namelist.append(nickname)
        print(nickname+' '+str(user_id))
    except:
        pass

i = 10000
while i < 19135000:
    threads = []
    for _ in range(100):
        thread = threading.Thread(target=get_nickname, args=(i,))
        threads.append(thread)
        thread.start()
        i += 1
    for thread in threads:
        thread.join()

# 保存到文件
with open('nickname.txt', 'w', encoding='utf-8') as f:
    f.write(dumps(namelist, ensure_ascii=False))

原理

这个程序的主要目的是从编程猫平台获取用户昵称,并将这些昵称保存到一个文件中。以下是程序的详细原理:

  1. 导入必要的模块
    • requests 模块用于发送HTTP请求。
    • json 模块用于处理JSON数据。
    • threading 模块用于实现多线程。
  2. 初始化变量
    • namelist 是一个空列表,用于存储获取到的用户昵称。
  3. 定义函数 get_nickname
    • 该函数接受一个用户ID作为参数。
    • 使用 requests.get 方法发送HTTP GET请求到编程猫的用户中心荣誉API,获取用户信息。
    • 使用 json.loads 方法将返回的JSON数据解析为Python字典。
    • 从字典中提取用户昵称,并将其添加到 namelist 列表中。
    • 打印用户昵称和用户ID。
    • 如果发生异常(例如用户不存在),则捕获异常并跳过。
  4. 多线程处理
    • 初始化用户ID i 为10000。
    • 使用一个无限循环来不断获取用户昵称,直到用户ID超过19135000。
    • 在每次循环中,创建100个线程,每个线程负责获取一个用户ID对应的昵称。
    • 启动所有线程,并等待所有线程完成。
    • 每次循环结束后,用户ID i 增加100。
  5. 保存结果到文件
    • 当用户ID超过19135000时,退出循环。
    • 使用 json.dumps 方法将 namelist 列表转换为JSON格式的字符串。
    • 将JSON字符串写入文件 nickname.txt 中,编码为UTF-8,确保中文字符正确显示。

注意事项

本程序已在github开源,戳我去看看

这个程序运行需要很长(真的很长!)的时间,所以如果可以的话请用github actions来运行,解放你的设备!

运行效果

看这里,github actions页面!