【问题标题】:Adding Parameter to URL to Iterate in Python将参数添加到 URL 以在 Python 中进行迭代
【发布时间】:2021-06-15 15:10:38
【问题描述】:

我正在编写一个 Python 脚本,我想在其中迭代 URL 末尾的 ID 值列表。

到目前为止,这是我的脚本,我想将 url 的 555 部分替换为 ID 值列表,以便脚本为每个值执行 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)

【问题讨论】:

  • 您心目中的价值观是什么?你能创建一个他们的列表吗?您可以遍历该列表并一一打印出来吗?
  • @quamrana - 这就是我需要帮助的地方。如何创建列表以在 URL 中遍历它们?我不知道如何继续这部分。

标签: python api post parameters iterator


【解决方案1】:

您可以使用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

【讨论】:

  • 我收到以下错误:response = requests.request("POST", f"{base_url}/{id}", headers=headers) ^ SyntaxError: invalid syntax
  • 这很奇怪,对我来说很好用。可能是 f 字符串的问题,请使用更新后的问题重试(我改为 base_url + str(id) 而不是 f"{base_url}/{id}"
  • 非常感谢您的帮助。这对我有用。在我的研究中,由于我使用 Python 2.7 的环境,我的 f-string 似乎可能出现错误,因此我需要尝试更新版本的 Python 并查看它是否有效。
猜你喜欢
  • 2020-09-05
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2019-12-14
  • 2015-04-24
相关资源
最近更新 更多