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

Python 爬虫 抓取百度图片资源 压缩图片

2017-09-22 10:30 513 查看
#!/usr/bin/python
# -*- coding:utf-8 -*-
"爬百度图片"
import re
import requests
import sys

word = raw_input(unicode('输入关键字:','utf-8').encode('gb2312'))
if word != '':
data = {'tn': 'baiduimage','lm': '-1', 'cl': '2', 'ipn': 'r', 'st': '-1', 'ct': '201326592', 'nc': '1', 'istype': '2', 'word': word.decode(sys.stdin.encoding).encode('utf8'), 'fmq':'1506045691737_R', 'fm': 'result', 'f': '3', 'sf': '1', 'se': '1'}
r = requests.get('http://image.baidu.com/search/index', params=data)
html = r.text
print r.url
pic_url = re.findall('"objURL":"(.*?)",',html,re.S)
i=0
for img in pic_url:
try:
pic = requests.get(img, timeout=10)
except requests.exceptions.ConnectionError:
print u'【错误】当前图片无法下载'
continue
img_path = 'up_load_img\\' + str(i) + '.jpg'
fp = open(img_path, 'wb')
fp.write(pic.content)
fp.close()
i += 1
bili = int(float(i) /len(pic_url) *100)
print u"正在下载第%d张图片————————%d%"%(i,bili)
print u"下载完成..."
else:
print u"请输入关键字"


运行结果

正在下载第27张图片————————90%

正在下载第28张图片————————93%

正在下载第29张图片————————96%

正在下载第30张图片————————100%

下载完成...

查看图片文件下,多出了30张图片

压缩图片:这里使用了熊猫压图

将下文件放在需要压缩的图片文件夹下面

#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
from tinify import tinify
from os import path

def get_file_name():
# Initialize
max_size = 1024
compressed_size = 100
dic_path = os.getcwd()
f_list = os.listdir(os.getcwd())
out_list = {}

# Read compress history
f_history = open("history_compressed.txt", 'a+')
f_history.seek(0)
x=1
print u'开始压缩请等待...'
for i in f_list:
file = dic_path + "/" + os.path.basename(i)
# print file
# buffer_file = path.splitext(file)[0] + "Copy" + path.splitext(file)[1]
# method参数可以为以下三种模式:
# scale:如果method参数设置为scale,则只需要提供width或者height其中的一个。服务器会根据原比例缩小图片。如果同时提供width和height将会报错。
# fit:如果method参数设置为fit,则需要同时提供width和height以确定一个范围,缩小后的图片会保证尽量填充该区域。
# cover:如果method参数设置为cover,缩小后的图片会填满width和height提供的区域,在必要的情况下服务器会根据一套算法保留他们认为的主要内容,其他部分会被裁剪
# 获取压缩前的大小
file_size1 = os.path.getsize(file)
tinify.from_file(file).resize(method="scale", width=200).to_file(file)
file_size2 = os.path.getsize(file)
#获取压缩后的大小
bili = int(float(x) / len(f_list) * 100)
print u"正在压缩第%s张图片------%d%"%(x,bili)
print u"压缩前%d压缩后%d"%(file_size1,file_size2)
f_history.write('%s压缩前%d压缩后%d\n'%(file,file_size1,file_size2))
x+=1
f_history.flush()
f_history.close()
return

tinify.key = "申请的KEY"
get_file_name()
print(u"执行完成...")


执行过后

开始压缩请等待...

正在压缩第1张图片------5%

压缩前90608压缩后15784

正在压缩第2张图片------10%

压缩前42246压缩后13361

正在压缩第3张图片------15%

压缩前50793压缩后19096

正在压缩第4张图片------21%

压缩前16934压缩后6943

正在压缩第5张图片------26%
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python