Coursera课程《Using Python to Access Web Data》 密歇根大学

Week6 JSON and the REST Architecture

13.5 JavaScript Object Notation(JSON)

JSON是一种相比于XML更简单的格式,而且现在在互联网上非常普遍。XML是很强大,但是很多时候我们并不需要使用这么强大的格式,我们就能完成我们的任务。

import json
data = '''{
"name": "Chuck",
"phone": {
"type": "intl",
"number": "+1 734 303 4456"
},
"email": {
"hide": "yes"
}
}''' info = json.loads(data)
print('Name:',info["name"])
print('Hide:',info["email"]["hide"])

JSON表示数据是用一种list与dictionary的组合的结构。

13.6 Service Oriented

有一些小应用需要使用其他网页提供的一些服务的时候,就会需要使用这些网页发布的“规则”来进行获取服务,这种我们叫做API(Application Program Interface)。

13.7 Using Application Programming Interfaces

以下是使用Google的geocoding API的代码。

import urllib.request, urllib.parse, urllib.error
import json # Note that Google is increasingly requiring keys
# for this API
serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?' while True:
address = input('Enter location: ')
if len(address) < 1: break url = serviceurl + urllib.parse.urlencode(
{'address': address}) print('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read().decode()
print('Retrieved', len(data), 'characters') try:
js = json.loads(data)
except:
js = None if not js or 'status' not in js or js['status'] != 'OK':
print('==== Failure To Retrieve ====')
print(data)
continue print(json.dumps(js, indent=4)) lat = js["results"][0]["geometry"]["location"]["lat"]
lng = js["results"][0]["geometry"]["location"]["lng"]
print('lat', lat, 'lng', lng)
location = js['results'][0]['formatted_address']
print(location)

使用这个API,Google可以给我们返回我们输入的地点的经纬度之类的信息。

需要说明的是,json.dumps()用于将dict类型的数据转成str,因为如果直接将dict类型的数据写入json文件中会发生报错,因此在将数据写入时需要用到该函数。而它带的那个参数indent可以使json显示为树形结构,更加方便阅读。

13.8 Securing API Requests

这里我们讲的Twitter的API和之前的Google Map APIs不同,它需要我们去注册,获得他们的API Key。

import urllib.request, urllib.parse, urllib.error
import twurl
import json
import ssl # https://apps.twitter.com/
# Create App and get the four strings, put them in hidden.py TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json' # Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE while True:
print('')
acct = input('Enter Twitter Account:')
if (len(acct) < 1): break
url = twurl.augment(TWITTER_URL,
{'screen_name': acct, 'count': '5'})
print('Retrieving', url)
connection = urllib.request.urlopen(url, context=ctx)
data = connection.read().decode() js = json.loads(data)
print(json.dumps(js, indent=2)) headers = dict(connection.getheaders())
print('Remaining', headers['x-rate-limit-remaining']) for u in js['users']:
print(u['screen_name'])
if 'status' not in u:
print(' * No status found')
continue
s = u['status']['text']
print(' ', s[:50])

注意,headers = dict(connection.getheaders())这行代码是来获取headers的。

print('Remaining', headers['x-rate-limit-remaining'])是获取限速的剩余次数的,是写在header里的。(好像只有Twitter API配置了这个?)

而我们要在Twitter的网页上获取下面代码里的这些东西。不然,我们是没法访问Twitter的服务的。

def oauth():
return {"consumer_key": "h7Lu...Ng",
"consumer_secret": "dNKenAC3New...mmn7Q",
"token_key": "10185562-eibxCp9n2...P4GEQQOSGI",
"token_secret": "H0ycCFemmC4wyf1...qoIpBo"}

以下是使用叫作OAuth的一种协议来获取访问Twitter的URL的。

import urllib.request, urllib.parse, urllib.error
import oauth
import hidden # https://apps.twitter.com/
# Create App and get the four strings, put them in hidden.py def augment(url, parameters):
secrets = hidden.oauth()
consumer = oauth.OAuthConsumer(secrets['consumer_key'],
secrets['consumer_secret'])
token = oauth.OAuthToken(secrets['token_key'], secrets['token_secret']) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
token=token, http_method='GET', http_url=url,
parameters=parameters)
oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(),
consumer, token)
return oauth_request.to_url() def test_me():
print('* Calling Twitter...')
url = augment('https://api.twitter.com/1.1/statuses/user_timeline.json',
{'screen_name': 'drchuck', 'count': '2'})
print(url)
connection = urllib.request.urlopen(url)
data = connection.read()
print(data)
headers = dict(connection.getheaders())
print(headers)

作业代码1

import urllib.request, urllib.parse, urllib.error
import json url=input('Enter location: ')
print('Retrieving ',url)
uh = urllib.request.urlopen(url)
data = uh.read().decode()
print('Retrieved', len(data), 'characters')
info = json.loads(data) sum = 0
count = 0
for item in info["comments"]:
sum = sum + item["count"]
count+=1
print('Count: ', count)
print('Sum: ',sum)

作业代码2

import urllib.request, urllib.parse, urllib.error
import json # Note that Google is increasingly requiring keys
# for this API
serviceurl = 'http://py4e-data.dr-chuck.net/geojson?' while True:
address = input('Enter location: ')
if len(address) < 1: break url = serviceurl + urllib.parse.urlencode({'address': address}) print('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read().decode()
print('Retrieved', len(data), 'characters') try:
js = json.loads(data)
except:
js = None if not js or 'status' not in js or js['status'] != 'OK':
print('==== Failure To Retrieve ====')
print(data)
continue place_id = js["results"][0]["place_id"]
print('Place id ',place_id)

【Python学习笔记】Coursera课程《Using Python to Access Web Data》 密歇根大学 Charles Severance——Week6 JSON and the REST Architecture课堂笔记的更多相关文章

  1. 【Python学习笔记】Coursera课程《Python Data Structures》 密歇根大学 Charles Severance——Week6 Tuple课堂笔记

    Coursera课程<Python Data Structures> 密歇根大学 Charles Severance Week6 Tuple 10 Tuples 10.1 Tuples A ...

  2. 【Python学习笔记】Coursera课程《Using Python to Access Web Data 》 密歇根大学 Charles Severance——Week2 Regular Expressions课堂笔记

    Coursera课程<Using Python to Access Web Data > 密歇根大学 Charles Severance Week2 Regular Expressions ...

  3. 【Python学习笔记】Coursera课程《Using Databases with Python》 密歇根大学 Charles Severance——Week4 Many-to-Many Relationships in SQL课堂笔记

    Coursera课程<Using Databases with Python> 密歇根大学 Week4 Many-to-Many Relationships in SQL 15.8 Man ...

  4. Coursera课程《Python数据结构》中课程目录

    Python Data Structures Python Data Structures is the second course in the specialization Python for ...

  5. 《Using Python to Access Web Data》Week4 Programs that Surf the Web 课堂笔记

    Coursera课程<Using Python to Access Web Data> 密歇根大学 Week4 Programs that Surf the Web 12.3 Unicod ...

  6. 《Using Python to Access Web Data》 Week5 Web Services and XML 课堂笔记

    Coursera课程<Using Python to Access Web Data> 密歇根大学 Week5 Web Services and XML 13.1 Data on the ...

  7. 《Using Python to Access Web Data》 Week3 Networks and Sockets 课堂笔记

    Coursera课程<Using Python to Access Web Data> 密歇根大学 Week3 Networks and Sockets 12.1 Networked Te ...

  8. Python学习入门基础教程(learning Python)--5.6 Python读文件操作高级

    前文5.2节和5.4节分别就Python下读文件操作做了基础性讲述和提升性介绍,但是仍有些问题,比如在5.4节里涉及到一个多次读文件的问题,实际上我们还没有完全阐述完毕,下面这个图片的问题在哪呢? 问 ...

  9. Python学习系列(四)Python 入门语法规则2

    Python学习系列(四)Python 入门语法规则2 2017-4-3 09:18:04 编码和解码 Unicode.gbk,utf8之间的关系 2.对于py2.7, 如果utf8>gbk, ...

随机推荐

  1. SpringBoot2.0(四) 远程调试

    和tomcat远程调试近似的配置,主要的配置如下所示: -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=10009 在 ...

  2. springBoot定制内嵌的Tomcat

    此篇仅介绍配置方式,详细配置内容百度查阅 工程结构: 可以通过配置的方式设置参数,如下 application.properties #配置tomcat端口 # server.port= 8888 # ...

  3. SPOJ - PHRASES

    题意: 给n个字符串,求出最长的子串.使得子串在每个字符串中不重叠地至少出现2次.输出子串长度. 题解: 用后缀数组求出height数组,之后二分答案.check时对height数组进行分组,并维护每 ...

  4. C#基础-连接Access与SQL Server

    1.连接Access数据库 string strConnection = "Provider=Microsoft.Ace.OleDb.12.0; Data Source=" + S ...

  5. POJ3421:X-factor Chains——题解

    http://poj.org/problem?id=3421 题目大意:一个数列,起始为1,终止为一给定数X,满足Xi < Xi+1 并且Xi | Xi+1. 求出数列最大长度和该长度下的情况数 ...

  6. AOJ. 数组训练.2016-11-17

    A题 #include <stdio.h> #include <stdlib.h> #define max 1000 __int64 a[max] = {0,1,1}; int ...

  7. 获取 exception 对象的字符串形式(接口服务返回给调用者)

    工具类: package com.taotao.common.utils; import java.io.PrintWriter; import java.io.StringWriter; publi ...

  8. hadoop压缩和解压

    最近有一个hadoop集群上的备份需求.源文件有几百G,如果直接复制太占用磁盘空间.将文件从hadoop集群下载到本地,压缩之后再上传到hadoop则太耗时间.于是想到能否直接在HDFS文件系统上进行 ...

  9. Leetcode 381. O(1) 时间插入、删除和获取随机元素 - 允许重复

    1.题目描述 设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构. 注意: 允许出现重复元素. insert(val):向集合中插入元素 val. remove(val):当 va ...

  10. radio is checked

    var is_rec =$("#is_rec_on").is(':checked'); if(is_rec){ $('.rec_img').css('display','block ...