Python.Calling a JSON API
2016-07-24 21:10
691 查看
The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data,
and retrieve the first place_id from
the JSON. A place ID is a textual identifier that uniquely identifies a place as within Google Maps.
Please run your program to find the place_id for this location:
Hint: The first seven characters of the place_id are
"ChIJ92o ..."
Python源码:
import urllib
import json
serviceurl = 'http://python-data.dr-chuck.net/geojson?'
while True:
address = raw_input('Enter location: ')
if len(address) < 1 : break
url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address})
print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
try: js = json.loads(str(data))
except: js = None
if 'status' not in js or js['status'] != 'OK':
print '==== Failure To Retrieve ===='
continue
place_id = js["results"][0]["place_id"]
print 'place_id',place_id
break
运行结果:
Enter location: Universidad Nacional de Colombia
Retrieving http://python-data.dr-chuck.net/geojson?sensor=false&address=Universidad+Nacional+de+Colombia place_id ChIJ92ouU_A3y5ERtjaGNPTPUGY
and retrieve the first place_id from
the JSON. A place ID is a textual identifier that uniquely identifies a place as within Google Maps.
Please run your program to find the place_id for this location:
Universidad Nacional de Colombia
Hint: The first seven characters of the place_id are
"ChIJ92o ..."
Python源码:
import urllib
import json
serviceurl = 'http://python-data.dr-chuck.net/geojson?'
while True:
address = raw_input('Enter location: ')
if len(address) < 1 : break
url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address})
print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
try: js = json.loads(str(data))
except: js = None
if 'status' not in js or js['status'] != 'OK':
print '==== Failure To Retrieve ===='
continue
place_id = js["results"][0]["place_id"]
print 'place_id',place_id
break
运行结果:
Enter location: Universidad Nacional de Colombia
Retrieving http://python-data.dr-chuck.net/geojson?sensor=false&address=Universidad+Nacional+de+Colombia place_id ChIJ92ouU_A3y5ERtjaGNPTPUGY
相关文章推荐
- 以写代学:python 格式化操作符
- python核心编程第九章练习
- Python安装及环境配置
- python之try-except语句
- python学习之开发小游戏---skier(滑雪的人)
- Python爬虫进阶三之Scrapy框架安装配置
- Python.Extracting Data from JSON
- python读取excel文件
- Python函数第四节
- python核心编程第八章练习
- python核心编程第七章练习
- Python学习笔记20:Python Web编程
- python核心编程作业--正则表达式和图形界面--电影搜索器(电影天堂)
- Python开发柜员机系统
- Python学习笔记19:Python图形用户界面编程
- Python学习笔记18:Python多线程编程
- python图像主色调(主颜色)提取,在hsv空间k均值迭代实现
- python 编译过程 从py文件到bytecode
- 利用Python实现简单的相似图片搜索
- 迅雷离线网页版API