如何用requests库获取nitrotype加载后的用户进度数据?
问题描述:
我尝试用requests库从nitrotype.com/racer/insert_name_here页面获取用户进度数据,写了如下代码:
import requests base_url = 'https://www.nitrotype.com/racer/' name = 'test' url = base_url + name page = requests.get(url) print(page.text)
但当前代码只能获取页面加载屏的内容,无法拿到加载完成后的目标数据。请问这个需求是否可行?如果可行,该怎么实现?
回答:
Absolutely, this is totally feasible! The issue with your current code is that NitroType loads user progress data dynamically using JavaScript after the initial page loads. The requests library only fetches the raw, unrendered HTML (which is why you’re seeing nothing but the loading screen). Here are two solid approaches to get the data you need:
方法1: 使用NitroType的公开API(推荐,更高效)
NitroType其实暴露了一个公开的API端点,直接以JSON格式返回用户数据——完全不需要解析HTML,这是最快最可靠的方法。
代码示例:
import requests username = 'test' api_url = f'https://www.nitrotype.com/api/v2/racers/{username}' # 添加User-Agent头,避免被站点拦截 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' } response = requests.get(api_url, headers=headers) if response.status_code == 200: user_data = response.json() # 提取具体进度数据,比如总比赛数、平均速度 print(f"总比赛次数: {user_data['racer']['stats']['races']}") print(f"平均速度: {user_data['racer']['stats']['speed']} WPM") else: print(f"获取数据失败: 状态码 {response.status_code}")
方法2: 使用Selenium模拟浏览器渲染
如果你更倾向于模拟真实用户的浏览器行为(比如API可能变更,或者需要更多页面上下文),可以用Selenium加载完整页面后提取渲染后的内容。
首先安装Selenium,并下载对应浏览器的驱动(比如Chrome的ChromeDriver):
pip install selenium
代码示例:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC username = 'test' url = f'https://www.nitrotype.com/racer/{username}' # 初始化Chrome驱动(确保ChromeDriver在你的环境PATH中) driver = webdriver.Chrome() driver.get(url) # 等待用户数据加载完成(可根据实际情况调整超时时间) try: # 等待包含进度数据的特定元素出现 total_races = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, '.stat--races .stat__value')) ) avg_speed = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, '.stat--speed .stat__value')) ) print(f"总比赛次数: {total_races.text}") print(f"平均速度: {avg_speed.text} WPM") finally: driver.quit()
这两种方法都能帮你获取到目标用户进度数据——除非有特殊需求,否则优先用API方案,因为它更简洁高效。
内容的提问来源于stack exchange,提问作者Systematic Error

