爬虫案例--图片下载器

需求分析:
"我想要图片,我又不想上网搜“
“最好还能自动下载”
……

这就是需求,实现两个功能,一是搜索图片,二是自动下载

主要工作在分析网页和数据处理

在这里插入图片描述

import requests
import os
import re

def req(url):
    headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36'}
    try:
        response = requests.get(url,headers=headers)
    except Exception as e:
        print('获取失败',e)
    else:
        html = response.text
        downloadpic(html,headers)

def downloadpic(html,headers):
    pic_url = re.findall('"objURL":"(.*?)"',html,re.S)
    count=0
    for each in pic_url:
        try:
            pic=requests.get(each,headers=headers)
            print(pic)
        except requests.exceptions.ConnectionError as f:
            print('图片无法下载')
        except Exception as e:
            print(e)
        else:
            pic.raise_for_status()
            if not os.path.exists(savedir):
                os.makedirs(savedir)
            else:
                tail = each.split(".")[-1]
                if tail not in ['png', 'jpg', 'gif', 'jpeg']:
           			 continue
                count+=1
                filename=strpic+ str(count)+tail
                fullfilename = os.path.join(savedir,filename)
                with open(fullfilename,'wb') as f:
                    f.write(pic.content)

if __name__ == '__main__':
    strpic = input('please input str:')
    url = 'http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=' + strpic
    savedir='/home/kiosk/Desktop/pictures'
    req(url)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值