怪不得都说压力山大,连山大服务器压力都太大了。并且编辑直接把图片挂到一个页面上是什么意思= =,一张照片8M+,反正外网速度台有限了。索性写个爬虫让他慢慢下吧,顺便当学习练手了。。。(PS:不知道为什么在windows下面在页面中用迅雷下载全部链接也无效,不知道什么原因?)
一共192组图片,前20组由于网页上顺序有问题,后期爬虫写完后又懒得改正则匹配了,所以就这样吧_(:з」∠)_
代码如下,一句句叠上来的,再简单不过了:
有python环境的可以自己直接保存后跑一下,不感兴趣的直接百度网盘下载吧
http://pan.baidu.com/s/1hSvH8
(感觉用sublimeText安装python支持后直接F5没有在linux下直接python 文件名速度快,不知道是不是因为测试时间不同情况下网速差异造成的)
#!/usr/bin/env python
#! -*- coding: utf-8 -*-
import urllib,urllib2
import re
import time
#返回网页源代码
def getHtml(url):
# print 'Start Downloading Html Source Code'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent' : user_agent }
req = urllib2.Request(url,headers = headers)
html = urllib2.urlopen(req)
srcCode = html.read()
#print srcCode
return srcCode
#srcCode 包含图片的网页
def getImg(srcCode,startNum,endNum):
#对网页中图片建立正则,并存为list
pattern = re.compile(r'<a.*?href="(.*?)" title="第.*?组.JPG">')
imgSrcHtml = pattern.findall(srcCode)
print imgSrcHtml
#print len(imgSrcHtml)
num = startNum
# count = endPage - startPage
# for x in xrange(1,count):
for i in imgSrcHtml[startNum-1:endNum-1]:
# 补全链接,得到完整地址
i = 'http://www.online.sdu.edu.cn' + i
#print i
# return imageRealSrc
# for src in imageRealSrc:
# urllib.urlretrieve(src,'%s.jpg' % num)
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent' : user_agent }
req = urllib2.Request(i,headers = headers)
print "Downloading..."
print i
print "and saving as 第%s组.jpg\n" %(num+8)
##html = urllib2.urlopen(req,timeout = 5)
html = urllib2.urlopen(req)
f = open("./pics/" + u'第%s组.jpg' % (num+8), 'w+b')
f.write(html.read())
f.close()
num += 1
# try:
# html = urllib2.urlopen(req,timeout = 5)
# except Exception, e:
# print '抛出异常为:' + str(e)
# break
# try:
# f = open("./" + '%s.jpg' % num, 'w+b')
# f.write(html.read())
# f.close()
# num += 1
# except Exception, e:
# print '抛出异常为:' + str(e)
# # num +=1
# break
# time.sleep(5)
print '全部任务完成!'
ImgUrl = "http://www.online.sdu.edu.cn/news/article-17317.html"
print "共有184张照片,请依次输入开始数和结束数"
start = int(raw_input("Start number\n"))
end = int(raw_input("End number\n"))
print "Starting..."
getImg(getHtml(ImgUrl),start,end)