简体   繁体   English

Python从URL读取JSON

[英]Python read json from url

With Python 3, I want to read a JSON from url. 使用Python 3,我想从URL中读取JSON。 This is what I got: 这就是我得到的:

import json
import urllib.request
url_address = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
with urllib.request.urlopen(url_address) as url:
    data = json.loads(url.read())
print(data)

However, it gives: HTTPError: HTTP Error 400: Bad Request 但是,它给出: HTTPError: HTTP Error 400: Bad Request

To me below code is working- in Python 2.7 对我来说,以下代码在Python 2.7中有效

import json
from urllib import urlopen
url_address = ['https://api.twitter.com/1.1/statuses/user_timeline.json']
for i in url_address:
    resp = urlopen(i)
    data = json.loads(resp.read())
print(data)

Output- 输出 -

{u'errors': [{u'message': u'Bad Authentication data.', u'code': 215}]}

If you use requests module- 如果您使用requests模块-

import requests
url_address = ['https://api.twitter.com/1.1/statuses/user_timeline.json']
for i in url_address:
    resp = requests.get(i).json()
    print resp

Output- 输出 -

{u'errors': [{u'message': u'Bad Authentication data.', u'code': 215}]}

twitter is returning 400 code(bad request) so exception is firing. twitter正在返回400代码(错误请求),因此引发了异常。 you can use try...except in your code sample and read exception body to get response json {"errors":[{"code":215,"message":"Bad Authentication data."}]} 您可以在代码示例中使用try ... except并读取异常主体以获取响应json {“错误”:[{“代码”:215,“消息”:“错误的身份验证数据。”}]}

import json
import urllib.request
from urllib.error import HTTPError


try:

    url_address ='https://api.twitter.com/1.1/statuses/user_timeline.json'
    with urllib.request.urlopen(url_address) as url:
        data = json.loads(url.read())
        print(data)

except HTTPError as ex:
    print(ex.read())

I prefer aiohttp , it's asynchronous. 我更喜欢aiohttp ,它是异步的。 Last time I checked, urllib was blocking. 我上次检查时, urllib被阻止。 This means that it will prevent other parts of the script from running while it itself is running. 这意味着它将阻止脚本本身在运行时其他部分的运行。 Here's an example for aiohttp : 这是aiohttp的示例:

import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get('https://api.github.com/users/mralexgray/repos') as resp:

    print(await resp.json())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM