如何从网页获取JSON到Python脚本

Chr*_*s B 161 python json

在我的一个脚本中获得以下代码:

#
# url is defined above.
#
jsonurl = urlopen(url)

#
# While trying to debug, I put this in:
#
print jsonurl

#
# Was hoping text would contain the actual json crap from the URL, but seems not...
#
text = json.loads(jsonurl)
print text
Run Code Online (Sandbox Code Playgroud)

我想要做的是{{.....etc.....}}当我在Firefox中将它加载到我的脚本中时,获取我在URL上看到的内容,以便我可以解析它的值.我用谷歌搜索了一下,但我还没有找到一个很好的答案,如何实际{{...}}从URL结尾的东西.json到Python脚本中的对象.

Anu*_*yal 275

从URL获取数据,然后调用json.loadseg

Python2示例:

import urllib.request, json 
with urllib.request.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=google") as url:
    data = json.loads(url.read().decode())
    print(data)
Run Code Online (Sandbox Code Playgroud)

Python3示例:

import urllib, json
url = "http://maps.googleapis.com/maps/api/geocode/json?address=google"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data
Run Code Online (Sandbox Code Playgroud)

输出将导致如下所示:

{
"results" : [
    {
    "address_components" : [
        {
            "long_name" : "Charleston and Huff",
            "short_name" : "Charleston and Huff",
            "types" : [ "establishment", "point_of_interest" ]
        },
        {
            "long_name" : "Mountain View",
            "short_name" : "Mountain View",
            "types" : [ "locality", "political" ]
        },
        {
...
Run Code Online (Sandbox Code Playgroud)

  • 而不是使用消耗字符串使用的`json.loads`(这就是为什么需要`.read()`,而是使用`json.load(response)`. (29认同)

Jon*_*nts 100

我猜你真的想从URL获取数据:

jsonurl = urlopen(url)
text = json.loads(jsonurl.read()) # <-- read from it
Run Code Online (Sandbox Code Playgroud)

或者,在请求库中查看JSON解码器.

import requests
r = requests.get('someurl')
print r.json() # if response type was set to JSON, then you'll automatically have a JSON response here...
Run Code Online (Sandbox Code Playgroud)


Mar*_*oma 26

这将从使用Python 2.X和Python 3.X的网页获取JSON格式的字典:

#!/usr/bin/env python

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

import json


def get_jsonparsed_data(url):
    """
    Receive the content of ``url``, parse it as JSON and return the object.

    Parameters
    ----------
    url : str

    Returns
    -------
    dict
    """
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)


url = ("http://maps.googleapis.com/maps/api/geocode/json?"
       "address=googleplex&sensor=false")
print(get_jsonparsed_data(url))
Run Code Online (Sandbox Code Playgroud)

另请参阅:JSON的读写示例


小智 22

我发现这是使用Python 3时从网页获取JSON的最简单,最有效的方法:

import json,urllib.request
data = urllib.request.urlopen("https://api.github.com/users?since=100").read()
output = json.loads(data)
print (output)
Run Code Online (Sandbox Code Playgroud)

  • 这不起作用.你需要从urllib.request导入urlopen,即`来自urllib.request import urlopen` (3认同)

mam*_*mal 7

您需要import requests并使用 from json() 方法:

source = requests.get("url").json()
print(source)
Run Code Online (Sandbox Code Playgroud)

当然,这个方法也有效:

import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)
Run Code Online (Sandbox Code Playgroud)

json.loads将使用此将其解码为 Python 对象,例如 JSON 对象将成为 Python dict


bgp*_*ter 5

调用的所有urlopen()操作(根据docs)都返回一个类似文件的对象。一旦有了它,就需要调用其read()方法来在网络上实际提取JSON数据。

就像是:

jsonurl = urlopen(url)

text = json.loads(jsonurl.read())
print text
Run Code Online (Sandbox Code Playgroud)


avi*_*iso 5

在 Python 2 中, json.load() 将代替 json.loads() 工作

import json
import urllib

url = 'https://api.github.com/users?since=100'
output = json.load(urllib.urlopen(url))
print(output)
Run Code Online (Sandbox Code Playgroud)

不幸的是,这在 Python 3 中不起作用。 json.load 只是 json.loads 的包装器,它为类似文件的对象调用 read() 。json.loads 需要一个字符串对象,而 urllib.urlopen(url).read() 的输出是一个字节对象。因此,必须获得文件编码才能使其在 Python 3 中工作。

在这个例子中,我们查询编码的标头,如果没有得到,则回退到 utf-8。标头对象在 Python 2 和 3 之间是不同的,因此必须以不同的方式完成。使用请求可以避免这一切,但有时您需要坚持使用标准库。

import json
from six.moves.urllib.request import urlopen

DEFAULT_ENCODING = 'utf-8'
url = 'https://api.github.com/users?since=100'
urlResponse = urlopen(url)

if hasattr(urlResponse.headers, 'get_content_charset'):
    encoding = urlResponse.headers.get_content_charset(DEFAULT_ENCODING)
else:
    encoding = urlResponse.headers.getparam('charset') or DEFAULT_ENCODING

output = json.loads(urlResponse.read().decode(encoding))
print(output)
Run Code Online (Sandbox Code Playgroud)


小智 5

不确定为什么所有早期答案都使用json.loads. 所有你需要的是:

import json
from urllib.request import urlopen

f = urlopen("https://www.openml.org/d/40996/json")
j = json.load(f)
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为urlopen返回一个类似文件的对象,它与json.load.