一键自动下载百度美女图片

版权声明:原创文章转载请注明来源。 https://blog.csdn.net/samll_snail/article/details/84616480

我一直认为学习一个新东西成就感和兴趣很重要,前面几篇文章介绍了python的安装和使用,这篇文章以一个图片爬虫脚本例子来感受下python的魅力。大家可以参考之前关于python安装的文章复制并运行下面这个python脚本,同时为了方便更多小白读者快速体验python爬虫,我把文章中的python脚本打包成了一个可执行程序,大家可以直接双击运行程序即可下载你想要的图片,在本公众号后台回复关键字001即可获取该程序。

#coding:utf-8

import re
import requests
import os


def dowmloadPic(html, keyword):
    pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
    i = 1
    print('找到关键词:' + keyword + '的图片,开始下载图片...')
    for imageUrl in pic_url:
        print('正在下载第' + str(i) + '张图片,图片地址:' + str(imageUrl))
        try:
            pic = requests.get(imageUrl, timeout=10)
        except requests.exceptions.ConnectionError:
            print('当前图片下载失败')
            continue        
        dir = './images/' + keyword + '_' + str(i) + '.jpg'
        fp = open(dir, 'wb')
        fp.write(pic.content)
        fp.close()
        i += 1


if __name__ == '__main__':
    word = input("请输入你要搜索的图片: ")
    url = 'http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=' + word + '&ct=201326592&v=flip'
    print(url)
    result = requests.get(url)
    dirs = './images/'
    if not os.path.exists(dirs):
         os.makedirs(dirs)
    dowmloadPic(result.text, word)
    input()

1、输入你想搜索的图片

2、程序正在下载图片

3、图片下载成功

猜你喜欢

转载自blog.csdn.net/samll_snail/article/details/84616480