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 ...
随机推荐
- 高斯混合模型Gaussian Mixture Model (GMM)——通过增加 Model 的个数,我们可以任意地逼近任何连续的概率密分布
从几何上讲,单高斯分布模型在二维空间应该近似于椭圆,在三维空间上近似于椭球.遗憾的是在很多分类问题中,属于同一类别的样本点并不满足“椭圆”分布的特性.这就引入了高斯混合模型.——可以认为是基本假设! ...
- hdoj--1087--Super Jumping! Jumping! Jumping!(贪心)
Super Jumping! Jumping! Jumping! Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 ...
- Java并发包
刚看到一篇总结的比较全的JUC包总结,转载如下: 1. java.util.concurrent - Java 并发工具包 Java 5 添加了一个新的包到 Java 平台,java.util.con ...
- BZOJ 2957 分块
思路: 记录每栋楼楼顶与原点连线的斜率 那么一栋楼可见当且仅当前面所有楼的斜率都小于这栋楼 将n栋楼分为√(0.5*n*logn)块 每一块内维护一个单调上升子序列(注意不是LCS) 比如说4 1 2 ...
- MEF example code
public interface IObjectResolver { } public class ObjectResolver:IObjectResolver { private Compositi ...
- 学习篇之SVG
学习篇之SVG 一.use重用 与 g组合 xmlns变量实际上指示浏览器如何解释称为SVG的XML方言 <g></g> 组合 <use /> 重用 <ell ...
- [ RESTful ] [ API ] 有用的資訊
1. 淺談 REST 軟體架構風格 (Part.I) - 從了解 REST 到設計 RESTful https://blog.toright.com/posts/725/representationa ...
- MySQL构造测试数据
构造测试数据(笛卡尔积,6 次100 万) create table t1(id int, val varchar(80)); set @i := 0;create table tmp as sele ...
- Win10 UI入门 导航滑动条 求UWP工作
借鉴了 段博琼 大哥写的导航滑动,自己实现了一个类似安卓 IOS 导航滑动条 支持等比例 分割 tabView 支持动画滑动 效果如下图 WYGrid 你可以想象一个GridView itemsWr ...
- shell-6.其他配置文件和登录信息