在我的一个脚本中获得了以下代码:
#
# 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.....}}
内容加载到我的脚本中,这样我就可以从中解析出一个值。我用谷歌搜索了很多次,但我还没有找到一个好的答案,那就是如何将以.json
结尾的网址中的{{...}}
内容转换为Python脚本中的对象。
发布于 2012-10-19 07:26:29
我猜想您实际上是想从URL获取数据:
jsonurl = urlopen(url)
text = json.loads(jsonurl.read()) # <-- read from it
或者,查看requests库中的JSON decoder。
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...
发布于 2015-03-01 04:40:57
这将从包含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))
发布于 2016-02-24 03:59:52
我发现在使用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)
https://stackoverflow.com/questions/12965203
复制相似问题