Python 3 - 无法使用来自 API 的数据连接到 str

Python 3 - Can't concat to str with data from API

我目前正在使用 Python 3 开发一个使用 API 的工具。 API 的工作方式是通过来自 URL 的 http 请求进行传送。这个脚本背后的想法是它抓取所有数据的 url,然后将所有这些数据合并到一个 json 文件中。

当 运行 脚本向我显示以下回溯时:

File "/home/usr/anaconda3/envs/apitool/lib/python3.6/http/client.py", 
line 1064, in _send_output
+ b'\r\n'
TypeError: can't concat bytes to str

我通过查看之前的问题了解到 http 请求以字节为单位完成,而 JSON 以字符串形式存储。这是有道理的,我试图将字节显式转换为 utf-8 字符串,但仍然出现错误。

我是 Python 的新手,所以如果这看起来很基础,请原谅我。 我尝试遵循以前的解决方案,但 none 到目前为止对我有用。

提前致谢!

from urllib.request import urlopen
import json

URLs = [
# Some URLs that return JSON objects

]

json_list = []

for url in URLs:
   resp = urlopen(url, {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) 
   AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 
   Safari/537.36'})
   resp = resp.read().decode(resp.headers.get_content_charset() or 'utf-8')
   json_list.append(json.loads(resp))
   with open("abc.json", 'w') as fp:
       json.dump(json_list, fp, indent=2)

使用python-requests

此代码将从 url 接收到的所有 JSON 合并到一个 final.json 文件中。

import requests
import json

urls = ["https://api.chucknorris.io/jokes/random", 
        "http://api.icndb.com/jokes/random"]

final_data = {}

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36'}

for url in urls:
    data = requests.get(url, headers=headers).json()
    final_data.update(data)

with open('final.json', 'w') as f:
    json.dump(final_data, f)