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 ...
随机推荐
- node generator 模仿co
exports.run = function(fn ){ return function(onDone){ function thunk(tfn , ctx){ return function(sql ...
- android AppWidget的使用以及利用TimerTask实现widget的定时更新
第一步:首先是Widget的定义声明: 在资源文件下的xml目录中建立文件example_appwidget_info.xml: <?xml version="1.0" en ...
- ANT公布SVN WEB项目到TOMCAT以及利用post-commit自己主动提交编译更新
开发者在本地提交更新到SVNserver后.往往须要測试人员又一次測试.为了将更新内容即时反映到測试server.能够利用post-commit脚本将SVN更新同步到測试server中. (1)利用S ...
- listView 多个item布局
package kds.szkingdom.wo.android.adapter; import java.util.List; import android.content.Context; imp ...
- caioj1497&&bzoj3125: CITY
震惊!bzoj居然又被苏大佬D飞了... 这题煞笔模板题好吧. 然而bzojAC caiojWA%40??? 好强啊 今天早上发现是m打成n了囧 #include<cstdio> #inc ...
- lightoj--1354-- IP Checking(水题)
IP Checking Time Limit: 2000MS Memory Limit: 32768KB 64bit IO Format: %lld & %llu Submit Sta ...
- Redis学习笔记(三) 基本命令:Key操作
参考:http://doc.redisfans.com/ del key 删除给定的一个或多个Key(多个key用空格隔开),删除成功返回1,当key不存在时,返回0:例:del no-exist-k ...
- Spark SQL 编程API入门系列之Spark SQL的作用与使用方式
不多说,直接上干货! Spark程序中使用SparkSQL 轻松读取数据并使用SQL 查询,同时还能把这一过程和普通的Python/Java/Scala 程序代码结合在一起. CLI---Spark ...
- Hua Wei 机试题目一
一.身份证号码验证 题目描述: 我国公民的身份证号码特点如下:1. 长度为18位:2. 第1-17位只能为数字:3. 第18位可以是数字或者小写英文字母x.4. 身份证号码的第7~14位表示持有人生日 ...
- node.js连接数据库登录注册,修改用户(页面的ajax请求)
首先给大家看一下目录结构,结构如下: index.html 首页(显示所有的用户信息) login.html 登录页 register.html 注册页 db.js 配置链接数据库参数 dbhelpe ...