以下是一个示例代码,演示如何使用API每次只返回n行数据:
import requests
def get_data(api_url, n):
response = requests.get(api_url)
data = response.json()
# 只返回n行数据
return data[:n]
# 调用API并返回前5行数据
api_url = "http://example.com/api"
n = 5
result = get_data(api_url, n)
print(result)
在上面的示例中,get_data
函数接受API的URL和要返回的行数n作为参数。它发送一个GET请求到API,并使用response.json()
方法将响应数据解析为JSON格式。然后,它只返回前n行数据,通过切片操作data[:n]
实现。
你需要将api_url
替换为实际的API URL,并根据API返回的数据结构进行相应的处理。这只是一个基本示例,具体的实现方式可能会根据实际情况有所不同。