Python 调用百度API

作者: 姜康 | 来源:发表于2016-03-30 22:47 被阅读7907次

纸上得来终觉浅,绝知此事要躬行
今天稍微看了一下百度的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,对响应文本用正则表达式匹配,得到想要的数据。

超光速

相关文章

网友评论

  • S_6825: title = line['title']
    TypeError: string indices must be integers
    请问这个错误如何解决?
  • fd5005dd2339:import requests,sys,urllib,urllib2
    import json
    url = 'http://apis.baidu.com/txapi/mvtp/meinv'
    headers = {'apikey':'123456'}
    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 = "E:\\python\\"
    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()
    @姜康@喜欢睡觉和跑步君@sttomato
    大家帮我看看哪里出了错,初学者不太懂,谢谢!
    Traceback (most recent call last):
    File "E:/�����/python/Baidu/baidu.py", line 22, in <module>
    run()
    File "E:/�����/python/Baidu/baidu.py", line 18, in run
    for line in r['newslist']:
    KeyError: 'newslist'
    这是错误
  • 10ad5f168f27:你好,想请教一下,直接用requests,而不用调用API,可以提供下 代码么? 我想用reuqests访问一个API,但是需要API key, 可是 requests的参数里貌似没有设置api key的啊。
    姜康: @喜欢睡觉和跑步君 放在header里
  • 9275c2269a2d:你好,试了一下这个方法确实好用。不过有个问题,貌似每次只能爬下10张图,有一次读更多图的方法吗?改params并没有起作用
    9275c2269a2d: @jking54 嗯嗯,谢谢!
    姜康:@sttomato 这个是它API说明的,每天只更新10张,你可以找一些好一点的API,或者直接写一个爬图片的简单爬虫
  • 5b674470f1cd:👍感谢分享!

本文标题:Python 调用百度API

本文链接:https://www.haomeiwen.com/subject/lulelttx.html