如何从网页获取JSON到Python脚本 [英] How to get JSON from webpage into Python script

查看:250
本文介绍了如何从网页获取JSON到Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Got the following code in one of my scripts:

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

我想做的是获取在Firefox中将{{.....etc.....}}内容加载到脚本中时在URL上看到的内容,以便我可以解析出一个值.我已经用Google搜索了很多,但是关于如何将{{...}}内容实际上从以.json结尾的URL转换为Python脚本中的对象,我找不到很好的答案.

What I want to do is get the {{.....etc.....}} stuff that I see on the URL when I load it in Firefox into my script so I can parse a value out of it. I've Googled a ton but I haven't found a good answer as to how to actually get the {{...}} stuff from a URL ending in .json into an object in a Python script.

推荐答案

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

Get data from the URL and then call json.loads e.g.

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)

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

输出结果如下:

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

这篇关于如何从网页获取JSON到Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆