Python API循环中limit变量无法同步至请求URL问题排查
解决API分页循环请求中URL参数不更新的问题
问题描述
作为Python新手,在实现API分页循环请求时遇到问题:limit变量每次按预期递增100,但更新后的值无法传递到请求URL中。第二次循环时,URL仍为https://website.com/table1/?key=xxxx&limit=0,+100,期望应为https://website.com/table1/?key=xxxx&limit=100,+100。
原问题代码:
import requests import json import csv import pandas as pd import os os.remove('ladder.csv') os.remove('ladder.json') # Define the base URL and parameters base_url = 'https://website.com/table1/?key=xxxx' query_params = ",+" limit = 0 offset = 100 full_url = f'{base_url}{limit}{query_params}{offset}' # Function to fetch data from the API def fetch_data(full_url): response = requests.get(full_url) print (response.url) print (offset) if response.status_code == 200: return response.json() else: print(f"Error: {response.status_code}") print("Response content:", response.content) return None # Initialize variables all_data = [] has_more_data = True # Loop to fetch data with pagination while has_more_data: # Fetch data data = fetch_data(full_url) if data: # Debug: Print the response structure print(limit,offset) # Check if 'results' key exists in the response if 'ranking' in data: # Process the data (example: extend the all_data list with new records) all_data.extend(data['ranking']) # Check if there is more data to fetch if offset >= 1000: has_more_data = False else: if len(data['ranking']) < limit: has_more_data = False else: # Update the offset for the next request limit += offset else: print("Key 'ranking' not found in the response") has_more_data = False else: has_more_data = False # Example: Save all data to a JSON file with open('ladder.json', 'w') as f: json.dump(all_data, f, indent=4) print("Data fetching complete. Total records fetched:", len(all_data)) with open('ladder.json', encoding='utf-8') as inputfile: df = pd.read_json(inputfile) df.to_csv('ladder.csv', encoding='utf-8', index=False)
问题根源
full_url仅在代码初始化阶段生成一次,后续循环中即使limit变量更新,full_url的值也不会自动刷新,导致每次请求都使用初始的URL参数。
修正后的代码
import requests import json import csv import pandas as pd import os # 先判断文件是否存在再删除,避免文件不存在时抛出异常 for file in ['ladder.csv', 'ladder.json']: if os.path.exists(file): os.remove(file) # 定义基础URL和分页参数 base_url = 'https://website.com/table1/?key=xxxx' query_params = ",+" limit = 0 # 分页起始位置 offset = 100 # 每次请求获取的条数 # 从API获取数据的函数 def fetch_data(url): response = requests.get(url) print(f"当前请求URL: {response.url}") if response.status_code == 200: return response.json() else: print(f"请求错误,状态码: {response.status_code}") print("响应内容:", response.content) return None # 初始化变量 all_data = [] has_more_data = True # 分页循环请求数据 while has_more_data: # 每次循环重新构建URL,使用最新的limit值 full_url = f'{base_url}&limit={limit}{query_params}{offset}' # 获取数据 data = fetch_data(full_url) if data: print(f"当前起始位置: {limit}, 每次获取条数: {offset}") # 检查响应中是否包含'ranking'字段 if 'ranking' in data: # 合并新获取的数据 all_data.extend(data['ranking']) # 判断是否还有更多数据需要获取 # 当起始位置达到1000时停止请求(原逻辑) if limit >= 1000: has_more_data = False else: # 如果返回的数据条数小于每次请求的数量,说明已到最后一页 if len(data['ranking']) < offset: has_more_data = False else: # 更新下一次请求的起始位置 limit += offset else: print("响应中未找到'ranking'字段") has_more_data = False else: has_more_data = False # 将所有数据保存到JSON文件 with open('ladder.json', 'w') as f: json.dump(all_data, f, indent=4) print(f"数据获取完成,共获取 {len(all_data)} 条记录") # 转换为CSV格式保存 df = pd.read_json('ladder.json', encoding='utf-8') df.to_csv('ladder.csv', encoding='utf-8', index=False)
关键修改说明
- 动态生成请求URL:将
full_url的生成逻辑移到while循环内部,每次循环都会根据最新的limit值重新构建URL,确保参数更新生效; - 完善文件删除逻辑:增加文件存在判断,避免文件不存在时抛出异常;
- 修正分页终止条件:将
len(data['ranking']) < limit改为len(data['ranking']) < offset,因为offset是每次请求的数量,当返回数据不足该数量时,说明已到最后一页; - 变量名逻辑对齐:原代码中
offset >=1000的判断实际应为limit >=1000,因为limit是分页的起始位置,当起始位置达到1000时停止请求; - 优化调试输出:调整打印信息,更清晰地展示当前请求状态。
内容的提问来源于stack exchange,提问作者Trevor Turn
相关产品推荐
相关产品推荐

