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

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

#
# 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

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


从URL获取数据,然后调用json.loads例如

Python2例子

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

Python3例子

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)

输出结果会是这样的:

{
"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" ]
        },
        {
...

我会猜测你确实想从网址获取数据:

jsonurl = urlopen(url)
text = json.loads(jsonurl.read()) # <-- read from it

或者,查看请求库中的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...

这使用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))

另请参阅:读取和写入JSON示例

链接地址: http://www.djcxy.com/p/48695.html

上一篇: How to get JSON from webpage into Python script

下一篇: How can I use pickle to save a dict?