python爬虫 分页获取图片并下载
--刚接触python2天,想高速上手,就写了个爬虫,写完之后,成就感暴增,用起来顺手多了。

1.源代码
#coding=utf-8
import urllib
import re
class Page():
__slots__ = ('url', 'regex', 'arg' )
def __init__(this ,url ,regex ,arg ):
if not arg :
arg['download'] = False
arg['write'] = False
arg['outpath'] = ''
this.filter = Filter(url,{
'regex' : regex,
'custom' : arg['custom'] if arg.has_key('custom') else ''
})
this.url = url;
this.outpath = arg['outpath'] if arg.has_key('outpath') else ''
this.download =arg['download'] if arg.has_key('download') else False
this.write = arg['write'] if arg.has_key('write') else False
this.pagin = arg['pagin'] if arg.has_key('pagin') else False def start(this ,*prefix):
_pagin = this.pagin; _getHtml = this.getHtml;_prefix = '1';
if len(prefix) >= 1 : _prefix = prefix[0];
_getHtml(this.url ,_prefix);
if _pagin != False :
_start = _pagin['start']; _end = _pagin['end']; _rule = _pagin['rule'];
while _start <= _end :
_getHtml(_rule.replace('{page}',str(_start)) ,str(_start));
_start += 1 def down(this ,url ,prefix):
try:
filename = str(prefix) + '_' + url[url.rfind("/")+1:]
urllib.urlretrieve(url, this.outpath + filename);
print 'download-succeed\t->',filename
except:
print 'download->failed' def downs(this ,arr ,prefix):
for x in arr: this.down(x ,prefix); def writeFile(this ,arr):
_file = open(this.outpath + 'list.txt', 'a+')
try:
_file.writelines('\n\n'+'\n'.join(arr))
finally:
_file.close() def getHtml(this ,url ,prefix):
try:
_p = urllib.urlopen(url); html = _p.read(); _p.close()
html = unicode(html, "gb2312").encode("utf8")
arr = this.filter.execute(html ,prefix)
if this.download == True : this.downs(arr ,prefix);
if this.write == True : this.writeFile(arr);
except:
print "catch finally exception." class Filter():
def __init__(this ,url ,arg):
this.arg = arg
this.url = url def _getDomain(this):
url = this.url.split('/')
return url[0]+'//'+url[2] def _getRealUrl(this ,domain, url):
if url[0] == '/' : return domain + url;
if 'http://' in url : return url
#==============须要处理的字符串链接...
return domain + '/' +url; def execute(this ,html ,prefix):
_arg = this.arg; arr=[]; getRealUrl = this._getRealUrl;
its = re.finditer( _arg['regex'] ,html)
for match in its: arr.append(getRealUrl(this._getDomain() ,match.groups()[0]))
if _arg.has_key('custom') == True and _arg['custom'] != '' : _arg['custom'](arr ,prefix);
return arr def paginList(arr ,prefix):
num = 1;
for x in arr:
Page(x ,'<p><img\ssrc="(.*?)"\salt.*?</p>' ,{
'download' : True,
'outpath' : 'f:/temp/'
}).start(prefix+'_'+str(num));
num+=1 Page("http://www.netbian.com/fengjing/" ,'<li><a\shref="(.*? )"\s.*?\salt="(.*?)"\s.*?</li>' ,{
'custom' : paginList,
'pagin' : {
'start' : 2,
'end' : 10,
'rule' : 'http://www.netbian.com/fengjing/index_{page}.htm'
}
}).start()
2.执行例如以下
$ python getjpg.py
download-succeed -> 1_1_1bdbc1d1628a1f0ebd5fc60055ee506e.jpg
download-succeed -> 1_2_01b5b45171979aace617ab79299d7515.jpg
download-succeed -> 1_3_5698c42371add40501a328ef2c753b4d.jpg
download-succeed -> 1_4_f7219087ce29c474a777867b8e4755ed.jpg
download-succeed -> 1_5_58bf8172ea8bbc4cee0a0f8240f2b289.jpg
download-succeed -> 1_6_b4700f4bd96f90039ed662ebbf6c1f7c.jpg
download-succeed -> 1_7_8a637b3362acddac4671d9ad02e4a93f.jpg
download-succeed -> 1_8_f28e22908b68d6fbe42a15c4fcd62613.jpg
download-succeed -> 1_9_03806c0b3d33cfc3a3eb4ea3bbe8ca9e.jpg
download-succeed -> 1_10_cf26fb246e9b57c06e328af94e60450b.jpg
download-succeed -> 1_11_7563610f39bd29b8381201b95eed2624.jpg
download-succeed -> 1_12_8ccaccede13d0f377d0d8822243f3b6a.jpg
download-succeed -> 1_13_c95a0207db67a334be4812cec25d7023.jpg
download-succeed -> 1_14_71ce070aef91660e8dad60a5919ec505.jpg
download-succeed -> 1_15_9a647a8f449cdb3208a561b4c9fe2ce6.jpg
download-succeed -> 1_16_45d9992e3d5080cf14ef73da14066283.jpg
download-succeed -> 1_17_7bd84ee7d6f5cb911a3b1dbc6e0775c4.jpg
download-succeed -> 1_18_8397b9d434a187444c389ebff48bcfb5.jpg
download-succeed -> 2_1_f14e658f2464769756039e1ff18d5693.jpg
download-succeed -> 2_2_ad051a669008969800ccd324de056465.jpg
download-succeed -> 2_3_6190ffe369199b95274100996b02359a.jpg
download-succeed -> 2_4_f14dce28d960941781a12a57123076df.jpg
download-succeed -> 2_5_c7fb3b6f700339e9f3c9ee02474211eb.jpg
download-succeed -> 2_6_327f1a33b8c5989a2d014ea41565caef.jpg
...
3.结果例如以下
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
python爬虫 分页获取图片并下载的更多相关文章
- 如何用Python爬虫实现百度图片自动下载?
Github:https://github.com/nnngu/LearningNotes 制作爬虫的步骤 制作一个爬虫一般分以下几个步骤: 分析需求 分析网页源代码,配合开发者工具 编写正则表达式或 ...
- python爬虫3——获取审查元素(板野友美吧图片下载)
测试环境:python2.7 + beautifulsoup4.4.1 + selenium2.48.0 测试网址:http://tieba.baidu.com/p/2827883128 目的是下载该 ...
- Python 爬虫5——爬取并下载网页指定规格的图片
看完上篇文档之后,我们对于正则表达式已经有了基本的了解,其实学习最有效的办法就是带着问题和目的,这里我们假设有一个目标:获取某个网页上指定规格的图片的链接地址,并下载到本地. 一.实现步骤: 1.在浏 ...
- Python爬虫之网页图片抓取
一.引入 这段时间一直在学习Python的东西,以前就听说Python爬虫多厉害,正好现在学到这里,跟着小甲鱼的Python视频写了一个爬虫程序,能实现简单的网页图片下载. 二.代码 __author ...
- Python爬虫-萌妹子图片
最近发现一个可以看图的地方,一张张翻有点累,毕竟只有一只手(难道鼠标还能两只手翻?).能不能下到电脑上看呢,毕竟不用等网速,还可以预览多张,总之很方便,想怎么就怎么,是吧? 刚好这几天在学python ...
- python自动化登录获取图片登录验证码
主要记录一下:图片验证码1.获取登录界面的图片2.获取验证码位置3.在登录页面截取验证码保存4.调用百度api识别(目前准确率较高的识别图片api)本次登录的系统页面,可以看到图片验证码的位置登录页面 ...
- [Python爬虫] Selenium获取百度百科旅游景点的InfoBox消息盒
前面我讲述过如何通过BeautifulSoup获取维基百科的消息盒,同样可以通过Spider获取网站内容,最近学习了Selenium+Phantomjs后,准备利用它们获取百度百科的旅游景点消息盒(I ...
- Python 爬虫学习 网页图片下载
使用正则表达式匹配 # coding:utf-8 import re import urllib def get_content(url): """ Evilxr, &q ...
- 【Python】Python加lxml实现图片解析下载功能
1.下载网页:OpenHtml.py import urllib.request from urllib.parse import quote class HtmlLoader(object): de ...
随机推荐
- 为屏而生,为屏而死 - IT "精英”们的杯与具
为屏而生,为屏而死 - IT "精英"们的杯与具 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一 ...
- [CortexM0--stm32f0308]Low Power Mode
问题描写叙述 stm32f0308正常是运行在Run mode下.这样的mode是在reset之后的默认模式.Low Power Mode.即低功耗模式.用于在IC空暇时能够考虑选择进入.使系统耗能减 ...
- DISCUZ站点DIY后,导致DIY功能失效,无法在前台删除已创建的DIY功能解决的方法
DISCUZ站点DIY后.导致DIY功能失效,无法在前台删除已创建的DIY功能解决的方法.这是一个常常会遇到的问题.在程序调试过程中常常的会遇到这种问题.这里提供一个自己常常使用的解决的方法,供遇到这 ...
- lpad&rpad
lpad( string, padded_length, [ pad_string ] ) string: 准备被填充的字符串 padded_length: 填充之后的字符串长度 pad_string ...
- c++面向对象程序设计 谭浩强 第三章答案
2: #include <iostream> using namespace std; class Date {public: Date(int,int,int); Date(int,in ...
- Binary Indexed Tree 总结
特点 1. 针对 数组连续子序列累加和 问题(需要进行频繁的 update.sum 操作): 2. 并非是树型结构,只是逻辑上层次分明: 3. 可以通过 填坑法 来理解: 4. 中心思想:每一个整数都 ...
- QT-helloworld-QtCreater编写
前言:纯代码编写helloworld,解析代码含义. 一.新建空项目 新建->其他项目->Empty qmake Project 二.修改.pro文件 打开helloworld.pro文件 ...
- 枚举所有排列-STL中的next_permutation
枚举排列的常见方法有两种 一种是递归枚举 另一种是STL中的next_permutation //枚举所有排列的另一种方法就是从字典序最小排列开始,不停的调用"求下一个排列"的过程 ...
- centos 出现的问题
1.DNS问题,导致yum没得源 echo "nameserver 8.8.8.8">>/etc/resolv.conf 2.CentOS 7最小化安装后找不到‘ifc ...
- Windows下获取Dump文件以及进程下各线程调用栈的方法总结(转)
1. Dump文件的用途 Dump文件, 主要用于诊断一个进程的运行状态,尤其是碰到崩溃(Crash)或者挂起(hang)不响应时,需要分析它的工作状态. 除了平时常见的attach到这个进程, 分 ...