Python 3 - 无法使用API​​中的数据连接到str

时间:2017-08-07 14:54:32

标签: python json urllib

我目前正在使用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的新手,所以如果这看起来非常基本,请原谅我。 我试图遵循以前的解决方案,但到目前为止,它们都没有对我有效。

提前谢谢!

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)

1 个答案:

答案 0 :(得分:0)

使用python-requests

此代码将从网址收到的所有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)