向 URL 添加参数以在 Python 中迭代

问题描述

我有一个 Python 脚本,我正在处理它,我想在其中遍历 URL 末尾的 ID 值列表。

到目前为止,这是我的脚本,我想用一个 ID 值列表替换 url 的 555 部分,以便脚本对每个值都执行 POST。我怎样才能做到这一点?

#/bin/python3
import requests

url = "https://api.bleepbloop.com/v8/account/555"
headers = {"Accept": "application/json","Authorization": "Bearer 123456"}
response = requests.request("POST",url,headers=headers)
print(response.text)

解决方法

您可以使用 for 循环和 range 函数来创建 ID 列表:

#/bin/python3
import requests

base_url = "https://example.com/api/"
headers = {"Accept": "application/json","Authorization": "Bearer 123456"}
ids = [1,2,3,4] # or range(5)
for id in ids:
    response = requests.request("POST",base_url + str(id),headers=headers)
    print(response.text)

(工作示例:https://replit.com/@LukeStorry/67988932