Python 调用百度API
2017-05-16 09:42
651 查看
纸上得来终觉浅,绝知此事要躬行
今天稍微看了一下百度的API,试了一下如何调用那些API,发现其实是很容易的。
2.找到想要调用的API,这里我尝试的是百度美女图片
Paste_Image.png
Paste_Image.png
请求实例:
3.按照说明,自己稍作修改即可。
我的代码:(比较乱,请谅解)
首先引入库,这里需要用到requests,json
然后写api地址,参数表
发出请求,得到响应
定义一个存图片的函数
开始获取图片地址,保存
运行结果:
Paste_Image.png
对于其他的API的调用,原理都一样,按照要求发出请求,然后对响应文本进行解析,得到自己想要的数据。
下面再给一个api调用的实例代码,也是调用的图片(用有图片的例子来写,结果比较明显)
现在,是不是觉得很简单?当然,你也可以直接用requests,而不用调用API,对响应文本用正则表达式匹配,得到想要的数据。
今天稍微看了一下百度的API,试了一下如何调用那些API,发现其实是很容易的。
步骤:
1.访问百度API Store;2.找到想要调用的API,这里我尝试的是百度美女图片
Paste_Image.png
Paste_Image.png
请求实例:
# -*- coding: utf-8 -*- import sys, urllib, urllib2, json url = 'http://apis.baidu.com/txapi/mvtp/meinv?num=10' req = urllib2.Request(url) req.add_header("apikey", "您自己的apikey") resp = urllib2.urlopen(req) content = resp.read() if(content): print(content)
3.按照说明,自己稍作修改即可。
我的代码:(比较乱,请谅解)
首先引入库,这里需要用到requests,json
import requests import json
然后写api地址,参数表
url = 'http://apis.baidu.com/txapi/mvtp/meinv' headers = {'apikey':'*******(这里用你自己的apikey)'} params = {'num':'10'}
发出请求,得到响应
r = requests.get(url,params = params,headers=headers) r = r.json()
定义一个存图片的函数
def saveImage(imgUrl,imgName= 'default.jpg'): response = requests.get(imgUrl,stream = True) image = response.content dst = "f:\\baidu_img\\" path = dst+imgName print 'save the file:'+path+'\n' with open(path,'wb') as img: img.write(image) img.close()
开始获取图片地址,保存
def run(): for line in r['newslist']: title = line['title'] picUrl = line['picUrl'] saveImage(picUrl,imgName=title+'.jpg') run()
运行结果:
Paste_Image.png
对于其他的API的调用,原理都一样,按照要求发出请求,然后对响应文本进行解析,得到自己想要的数据。
下面再给一个api调用的实例代码,也是调用的图片(用有图片的例子来写,结果比较明显)
# -*- coding:utf-8 -*-
import requests
url_1 = "http://www.tngou.net/tnfs/api/list"
#url_2 = "http://www.tngou.net/tnfs/api/classify"
src_header = "http://tnfs.tngou.net/image"
headers = {'apikey':'*******(这里用你自己的apikey)'}
params_1 = {
'page':3,
'rows':20,
'id':6 #需根据classify结果才能知道
}
r = requests.get(url_1)
r = r.json()
#保存图片到本地路径
def saveImage(imgUrl,imgName= 'default.jpg'): response = requests.get(imgUrl,stream = True) image = response.content dst = "f:\\baidu_img\\" path = dst+imgName print 'save the file:'+path+'\n' with open(path,'wb') as img: img.write(image) img.close()
#开始
def run():
for line in r['tngou']:
title = line['title']
img = line['img']
src_path = src_header+img
saveImage(src_path,title+'.jpg')
run()
现在,是不是觉得很简单?当然,你也可以直接用requests,而不用调用API,对响应文本用正则表达式匹配,得到想要的数据。
相关文章推荐
- 【Python】调用百度REST API实现语音识别
- Python 3调用百度OCR API实现剪贴板文字识别
- Python3--批量爬取数据之调用百度api进行翻译
- Linux python PyQt5调用百度API实现图片文字转换
- python百度api调用
- python调用百度REST API实现语音识别
- 爬虫-python调用百度API/requests
- Python调用百度API之天气查询
- Python爬虫之百度API调用
- 实践项目五:python调用百度API实现自动检测翻译
- python 3调用百度OCR API实现剪贴板文字识别
- python爬虫之百度API调用方法
- 【Python】调用百度REST API实现语音识别
- 百度ocr开放api调用python代码
- ArcGIS10.1python调用Admin API完成几何服务的启动
- 调用百度api
- Android之调用百度API显示地图
- 使用python及百度API对百度poi数据进行爬取(一)
- python调用新浪微博API实践
- 毕设(一)C#的百度api调用