我需要将GET请求发送到1000个奇数URL,这些URL是从文件中提取的。这些URL的响应将转换为JSON对象,我将根据某些键迭代并打印值。在单个URL上执行时,此代码可以正常工作,但在循环中不起作用。
我认为这是由于将值添加到已经存在的字典中,所以我试图在循环结束时删除字典,但仍然是相同的问题
import requests
import objectpath
import json
user = ‘example_user’
password = ‘example_pass’
with open('rest.txt') as f: #rest.txt contains all the URLs
for url in f:
r = requests.get(url, auth=(user, password))
data = r.json()
jsonnn_tree = objectpath.Tree(data)
result_name = tuple(jsonnn_tree.execute('$..name'))
result_permission = tuple(jsonnn_tree.execute('$..permission'))
print(result_name)
print(result_permission)
f.close()
我希望O / P包含与键对应的值。
我得到的错误是
data = r.json()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py", line 889, in json
self.content.decode(encoding), **kwargs
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
答案 0 :(得分:0)
在get请求中使用的URL是错误的,因为变量url的输出包含换行符,我必须使用url = url.rstrip('\ n')来纠正此问题。问题已解决。
import requests
import objectpath
import json
user = ‘example_user’
password = ‘example_pass’
with open('rest.txt') as f: #rest.txt contains all the URLs
for url in f:
url = url.rstrip('\n')
r = requests.get(url, auth=(user, password))
data = r.json()
jsonnn_tree = objectpath.Tree(data)
result_name = tuple(jsonnn_tree.execute('$..name'))
result_permission = tuple(jsonnn_tree.execute('$..permission'))
print(result_name)
print(result_permission)
f.close()