一、什么是API?

API(ApplicationProgrammingInterface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。

例如:

http://apis.juhe.cn/ip/ip2addr?ip=112.112.11.11&key=appkey

返回的json格式的数据是:

{

"resultcode":"200",

"reason":"Return Successd!",

"result":{

"area":"江苏省苏州市",

"location":"电信"

}

}

返回的xml格式的数据是:

200

Return Successd!

江苏省苏州市

电信

二、使用Python调用API

1、使用Python对json格式的数据解析

import json

jsonString = '{"arrayOfNums":[{"number":0},{"number":1},{"number":2}],"arrayOfFruits":[{"fruit":"apple"},{"fruit":"banana"},{"fruit":"pear"}]}'

jsonObj = json.loads(jsonString)

print(jsonObj.get("arrayOfNums"))

print(jsonObj.get("arrayOfNums")[1])

print(jsonObj.get("arrayOfNums")[1].get("number") + jsonObj.get("arrayOfNums")[2].get("number"))

print(jsonObj.get("arrayOfFruits")[2].get("fruit"))

2、使用python调用聚合数据中的天气预报API

from urllib import urlencode

import urllib

import json

# 配置您申请的APPKey

appkey = "XXXXXXXXXXXXXXXXXXXXXXXX"

# 根据城市查询天气

def queryWeather(appkey, m="GET", city="广州", dtype="json"):

url = "http://v.juhe.cn/weather/index"

params = {

"cityname": city, # 要查询的城市,如:温州、上海、北京

"key": appkey, # 应用APPKEY(应用详细页查询)

"dtype": dtype, # 返回数据的格式,xml或json,默认json

}

params = urlencode(params, )

if m == "GET":

f = urllib.urlopen("%s?%s" % (url, params))

else:

f = urllib.urlopen(url, params)

content = f.read()

res = json.loads(content)

if res:

error_code = res["error_code"]

if error_code == 0:

# 成功请求

return res["result"]

else:

print "%s:%s" % (res["error_code"], res["reason"])

else:

print "request api error"

weather = queryWeather(appkey, "GET")

print weather

print urllib.unquote(weather.get("sk").get("wind_direction"))

3、使用python调用聚合数据中的查询IP地址API

from urllib import urlopen

import json

def getCountry(ipAddress, appkey):

response = urlopen("http://apis.juhe.cn/ip/ip2addr?ip=" + ipAddress + "&key=" + appkey).read().decode('utf-8')

responseJson = json.loads(response)

return responseJson.get("area")

# 配置您申请的APPKey

appkey = "84bd1042092e7b0e3265483f46febc80"

print(getCountry("61.135.169.121", appkey))

4、使用python 2.x 调用微博API

微博的Python 2.x SDK:

http://github.liaoxuefeng.com/sinaweibopy/

https://github.com/michaelliao/sinaweibopy

安装sdk

pip install sinaweibopy

实例代码

from weibo import APIClient

import webbrowser

## 1、个人微博的账号信息

APP_KEY = 'XXXXXX'

APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXX'

CALLBACK_URL = 'http://f.dataguru.cn'

## 2、请求授权

# 2.1

client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)

url = client.get_authorize_url()

# print(url)

# https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//f.dataguru.cn&response_type=code&client_id=2337575664

# 2.2

# 打开申请授权的网页,点击同意授权后会跳转到之前设置的回调网页(即CALLBACK_URL)

# 在回调页的浏览器地址栏里获取code(动态变化),用于第二步调用oauth2/access_token接口,获取授权后的access token

webbrowser.open_new(url)

# http://f.dataguru.cn/?code=6240f86a9c757ef6ea985cd28647f05a

code = '6240f86a9c757ef6ea985cd28647f05a'

## 3、获得授权

# 获取token 和 token的生命周期

r = client.request_access_token(code)

# print(r)

access_token = r.access_token

# print(access_token)

expires_in = r.expires_in

# print(expires_in)

## 4、为以后的API请求设置token

client.set_access_token(access_token, expires_in)

## 5、获取当前登录用户及其所关注(授权)用户的最新微博 statuses/home_timeline

# https://api.weibo.com/2/statuses/home_timeline.json

statuses = client.statuses.home_timeline.get(count=10)['statuses']

# print(statuses[1])

length = len(statuses)

print(length)

# 输出了部分信息

for i in range(0, length):

print(u'昵称:' + statuses[i]['user']['screen_name'])

print(u'简介:' + statuses[i]['user']['description'])

print(u'位置:' + statuses[i]['user']['location'])

print(u'微博:' + statuses[i]['text'])

## 6、获取最新的提到登录用户的微博列表,即@我的微博 statuses/mentions

# https://api.weibo.com/2/statuses/mentions.json

statuses = client.statuses.mentions.get()['statuses']

# print(statuses[1])

length = len(statuses)

print(length)

# 输出了部分信息

for i in range(0, length):

print(u'昵称:' + statuses[i]['user']['screen_name'])

print(u'简介:' + statuses[i]['user']['description'])

print(u'位置:' + statuses[i]['user']['location'])

print(u'微博:' + statuses[i]['text'])

print(u'时间:' + statuses[i]['created_at'])

5、使用python 3.x 调用微博API

微博的Python 3.x SDK:

https://github.com/nooperpudd/weibopy

安装sdk

pip install weibopy

实例代码

from weibopy import WeiboOauth2

import webbrowser

## 1、个人微博的账号信息

APP_KEY = 'XXXXXX'

APP_SECRET = 'XXXXXXXXXXXX'

CALLBACK_URL = 'http://f.dataguru.cn'

## 2、请求授权

# 2.1

client = WeiboOauth2(APP_KEY, APP_SECRET, CALLBACK_URL)

authorize_url = client.authorize_url

print(authorize_url)

# https://api.weibo.com/oauth2/authorize?redirect_uri=http%3A//f.dataguru.cn&response_type=code&client_id=2337575664

# 2.2

# 打开申请授权的网页,点击同意授权后会跳转到之前设置的回调网页(即CALLBACK_URL)

# 在回调页的浏览器地址栏里获取code(动态变化),用于第二步调用oauth2/access_token接口,获取授权后的access token

webbrowser.open_new(authorize_url)

# http://f.dataguru.cn/?code=4b156593e9dfdd16279bbcc9eb7817bf

code = '4b156593e9dfdd16279bbcc9eb7817bf'

## 3、获得授权

# 获取token 和 token的生命周期

r = client.auth_access(code)

# print(r)

access_token = r.get("access_token")

# print(access_token)

expires_in = r.expires_in

# print(expires_in)

## 4、为以后的API请求设置token

from weibopy import WeiboClient

client = WeiboClient(access_token)

## 5、获取当前登录用户及其所关注(授权)用户的最新微博 statuses/home_timeline

# https://api.weibo.com/2/statuses/home_timeline.json

result = client.get(suffix="statuses/home_timeline.json")

statuses = result.get("statuses")

# print(statuses[0])

length = len(statuses)

print(length)

# 输出了部分信息

for i in range(0, length):

print(u'昵称:' + statuses[i]['user']['screen_name'])

print(u'简介:' + statuses[i]['user']['description'])

print(u'位置:' + statuses[i]['user']['location'])

print(u'微博:' + statuses[i]['text'])

## 6、获取最新的提到登录用户的微博列表,即@我的微博 statuses/mentions

# https://api.weibo.com/2/statuses/mentions.json

result = client.get(suffix="statuses/mentions.json")

statuses = result.get("statuses")

# print(statuses[0])

length = len(statuses)

print(length)

# 输出了部分信息

for i in range(0, length):

print(u'昵称:' + statuses[i]['user']['screen_name'])

print(u'简介:' + statuses[i]['user']['description'])

print(u'位置:' + statuses[i]['user']['location'])

print(u'微博:' + statuses[i]['text'])

print(u'时间:' + statuses[i]['created_at'])

python 如何爬虫wind api数据_Python网络爬虫实战之十:利用API进行数据采集相关推荐

  1. python爬虫程序详解_Python网络爬虫之三种数据解析方式

    指定url 基于requests模块发起请求 获取响应对象中的数据 进行持久化存储 其实,在上述流程中还需要较为重要的一步,就是在持久化存储之前需要进行指定数据解析.因为大多数情况下的需求,我们都会指 ...

  2. python网络爬虫与信息提取视频_Python网络爬虫与信息提取入门5

    Part19 实例5:IP地址归属地的自动查询 怎么查询一个IP地址的归属呢?比如说某一个IP地址他是来自于北京.上海还是美国呢?我们用一个python 程序来判断.当然你要判断一个地址的归属地,你必 ...

  3. java爬取网页数据_Python网络爬虫实战(二)数据解析

    Python网络爬虫实战 (二)数据解析 本系列从零开始阐述如何编写Python网络爬虫,以及网络爬虫中容易遇到的问题,比如具有反爬,加密的网站,还有爬虫拿不到数据,以及登录验证等问题,会伴随大量网站 ...

  4. python爬虫微博热搜_Python网络爬虫之爬取微博热搜

    微博热搜的爬取较为简单,我只是用了lxml和requests两个库 url= https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&am ...

  5. python爬虫抓取动态网页数据_python网络爬虫抓取ajax动态网页数据:以抓取KFC门店地址为例...

    一,尝试用BeautifulSoup抓取 先打开KFC网站门店列表页面:http://www.kfc.com.cn/kfccda/storelist/index.aspx 可以看到门店列表如下图: 打 ...

  6. python滚动条翻页爬取数据_Python网络爬虫之Selenium 处理滚动条【第十四节】

    Selenium 处理滚动条selenium并不是万能的,有时候页面上操作无法实现的,这时候就需要借助JS来完成了 当页面上的元素超过一屏后,想操作屏幕下方的元素,是不能直接定位到,会报元素不可见的. ...

  7. python如何爬有道翻译_Python网络爬虫(八) - 利用有道词典实现一个简单翻译程序...

    目录: 1.爬虫前的分析 因为要实现有道翻译的翻译功能,就需要找到它的接口,打开审查元素,来到网络监听窗口(Network),查看API接口. 我们可以找到有道翻译的API接口,同时是以Post方式提 ...

  8. python爬虫登录12306失败_Python网络爬虫(selenium模拟登录12306网站)

    一.通过selenium自动登录12306官网 1.1 超级鹰打码平台API,创建chaojiyin.py文件 #!/usr/bin/env python#coding:utf-8 importreq ...

  9. python爬取去哪儿网_python网络爬虫(12)去哪网酒店信息爬取

    目的意义 爬取某地的酒店价格信息,示例使用selenium在Firefox中的使用. 来源 少部分来源于书.python爬虫开发与项目实战 构造 本次使用简易的方案,模拟浏览器访问,然后输入字段,查找 ...

最新文章

  1. python实验过程心得体会_Python中django学习心得
  2. 车联网支持实现无人驾驶的思考
  3. 龙岗网络推广解析有关网站SEO排名上去了,但没实际性点击的问题
  4. access统计没有选课的人数_当代大学生发愁求职就业,更发愁“选课”,自主选课变成了负担...
  5. Linux C语言 文件操作
  6. sourceinsight安装记录
  7. Python3入门机器学习经典算法与应用 第3章 Jupyter Notebook numpy.array 基础 numpy.array的基本操作
  8. Php货币计算怎么样才严谨,php怎样【货币问答】- php怎样所有答案 - 联合货币
  9. TJUPT 无法与服务器建立连接问题的解决方法
  10. 解决阿里云oss 图片跨域问题
  11. 分布式计算 lab2 Java RMI
  12. 一些noip模拟题一句话题解
  13. 纯css实现翻书效果
  14. [分形学] Julia Set (茱莉亚集) VC 源代码
  15. 造成503 service unavailable常见的原因以及解决方法
  16. 爬虫有道翻译接口+图片文字识别
  17. 以智能钻井为例,深度解析数字油田的智能化建设
  18. 记一次投票系统维护以及防止刷票springboot+redis
  19. 什么是drop-in item renderer
  20. magic魔术师分身问题

热门文章

  1. python if main_python if __name__ == 'main' 的作用和原理()
  2. 大白菜U盘安装win10操作系统
  3. Codeforces 刷水记录
  4. 很好的网站,你懂的,不喜勿喷
  5. 一图看懂信用报告在线查询指南
  6. 物联网平台由哪些部分组成
  7. Hyperlegder Fabric监控:blockchain-explorer
  8. 《基于海思35xx nnie引擎进行经典目标检测算法模型推理》视频课程介绍
  9. 机房管理系列(1) 联想保护系统EDU7.5在同传CMOS参数后奔溃的解决办法
  10. 画太极(echarts)