嗨,我试图迭代一个字典,但不工作,我已经尝试diferents方式,但不明白这是代码。
import requests
items_id = ['MLM594466110']
headers = {
'Content-Type': 'application/json',
}
params = (
('access_token', 'MY_ACCESS_TOKEN'),
)
for i in items_id:
data = '{"text":"Text","item_id":"{i}"}'
response = requests.post('https://api.webpage.com/questions/{i}', headers=headers, params=params, data=data)
print(response)
形成你的 data
对象会有一点不同,因为它使用嵌套的字符串值。所以,最简单的解决方案是使用 %
这样的记法。
for i in items_id:
data = '{"text":"Text","item_id":"{%s}"}' %str(i) #<--- notice using %s here which stands for string
response = requests.post(f'https://api.webpage.com/questions/{i}', headers=headers, params=params, data=data) #<--- notice adding `f` just after post(