【爬虫】码了个毕业照爬虫

怪不得都说压力山大,连山大服务器压力都太大了。并且编辑直接把图片挂到一个页面上是什么意思= =,一张照片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)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江前云后

文章结束的标识:打赏链接

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值