您的位置:首页 > 编程语言 > Python开发

Python 调用百度API

2017-05-16 09:42 651 查看
纸上得来终觉浅,绝知此事要躬行
今天稍微看了一下百度的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,对响应文本用正则表达式匹配,得到想要的数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: