Python爬虫之路——简单网页抓图升级版(添加多线程支持)

转载自我的博客:http://www.mylonly.com/archives/1418.html

经过两个晚上的奋斗。将上一篇文章介绍的爬虫略微改进了下(Python爬虫之路——简单网页抓图),主要是将获取图片链接任务和下载图片任务用线程分开来处理了,并且这次的爬虫不只能够爬第一页的图片链接的,整个http://desk.zol.com.cn/meinv/以下的图片都会被爬到,并且提供了多种分辨率图片的文件下载,详细设置方法代码凝视里面有介绍。

这次的代码仍然有点不足,Ctrl-C无法终止程序,应该是线程无法响应主程序的终止消息导致的,(最好放在后台跑程序)还有线程的分配还能够优化的更好一点。兴许会陆续改进.

#coding: utf-8 #############################################################
# File Name: main.py
# Author: mylonly
# mail: [email protected]
# Created Time: Wed 11 Jun 2014 08:22:12 PM CST
#########################################################################
#!/usr/bin/python

import re,urllib2,HTMLParser,threading,Queue,time

#各图集入口链接
htmlDoorList = []
#包括图片的Hmtl链接
htmlUrlList = []
#图片Url链接Queue
imageUrlList = Queue.Queue(0)
#捕获图片数量
imageGetCount = 0
#已下载图片数量
imageDownloadCount = 0
#每一个图集的起始地址。用于推断终止
nextHtmlUrl = ‘‘
#本地保存路径
localSavePath = ‘/data/1920x1080/‘

#假设你想下你须要的分辨率的,请改动replace_str,有例如以下分辨率可供选择1920x1200。1980x1920,1680x1050,1600x900,1440x900,1366x768,1280x1024,1024x768,1280x800
replace_str = ‘1920x1080‘

replaced_str = ‘960x600‘

#内页分析处理类
class ImageHtmlParser(HTMLParser.HTMLParser):
	def __init__(self):
		self.nextUrl = ‘‘
		HTMLParser.HTMLParser.__init__(self)
	def handle_starttag(self,tag,attrs):
		global imageUrlList
		if(tag == ‘img‘ and len(attrs) > 2 ):
			if(attrs[0] == (‘id‘,‘bigImg‘)):
				url = attrs[1][1]
				url = url.replace(replaced_str,replace_str)
				imageUrlList.put(url)
				global imageGetCount
				imageGetCount = imageGetCount + 1
				print url
		elif(tag == ‘a‘ and len(attrs) == 4):
			if(attrs[0] == (‘id‘,‘pageNext‘) and attrs[1] == (‘class‘,‘next‘)):
				global nextHtmlUrl
				nextHtmlUrl = attrs[2][1];

#首页分析类
class IndexHtmlParser(HTMLParser.HTMLParser):
	def __init__(self):
		self.urlList = []
		self.index = 0
		self.nextUrl = ‘‘
		self.tagList = [‘li‘,‘a‘]
		self.classList = [‘photo-list-padding‘,‘pic‘]
		HTMLParser.HTMLParser.__init__(self)
	def handle_starttag(self,tag,attrs):
		if(tag == self.tagList[self.index]):
			for attr in attrs:
				if (attr[1] == self.classList[self.index]):
					if(self.index == 0):
						#第一层找到了
						self.index = 1
					else:
						#第二层找到了
						self.index = 0
						print attrs[1][1]
						self.urlList.append(attrs[1][1])
						break
		elif(tag == ‘a‘):
			for attr in attrs:
				if (attr[0] == ‘id‘ and attr[1] == ‘pageNext‘):
					self.nextUrl = attrs[1][1]
					print ‘nextUrl:‘,self.nextUrl
					break

#首页Hmtl解析器
indexParser = IndexHtmlParser()
#内页Html解析器
imageParser = ImageHtmlParser()

#依据首页得到全部入口链接
print ‘開始扫描首页...‘
host = ‘http://desk.zol.com.cn‘
indexUrl = ‘/meinv/‘
while (indexUrl != ‘‘):
	print ‘正在抓取网页:‘,host+indexUrl
	request = urllib2.Request(host+indexUrl)
	try:
		m = urllib2.urlopen(request)
		con = m.read()
		indexParser.feed(con)
		if (indexUrl == indexParser.nextUrl):
			break
		else:
			indexUrl = indexParser.nextUrl
	except urllib2.URLError,e:
		print e.reason

print ‘首页扫描完毕,全部图集链接已获得:‘
htmlDoorList = indexParser.urlList

#依据入口链接得到全部图片的url
class getImageUrl(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
	def run(self):
		for door in htmlDoorList:
			print ‘開始获取图片地址,入口地址为:‘,door
			global nextHtmlUrl
			nextHtmlUrl = ‘‘
			while(door != ‘‘):
				print ‘開始从网页%s获取图片...‘% (host+door)
				if(nextHtmlUrl != ‘‘):
					request = urllib2.Request(host+nextHtmlUrl)
				else:
					request = urllib2.Request(host+door)
				try:
					m = urllib2.urlopen(request)
					con = m.read()
					imageParser.feed(con)
					print ‘下一个页面地址为:‘,nextHtmlUrl
					if(door == nextHtmlUrl):
						break
				except urllib2.URLError,e:
					print e.reason
		print ‘全部图片地址均已获得:‘,imageUrlList

class getImage(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
	def run(self):
		global imageUrlList
		print ‘開始下载图片...‘
		while(True):
			print ‘眼下捕获图片数量:‘,imageGetCount
			print ‘已下载图片数量:‘,imageDownloadCount
			image = imageUrlList.get()
			print ‘下载文件路径:‘,image
			try:
				cont = urllib2.urlopen(image).read()
				patter = ‘[0-9]*\.jpg‘;
				match = re.search(patter,image);
				if match:
					print ‘正在下载文件:‘,match.group()
					filename = localSavePath+match.group()
					f = open(filename,‘wb‘)
					f.write(cont)
					f.close()
					global imageDownloadCount
					imageDownloadCount = imageDownloadCount + 1
				else:
					print ‘no match‘
				if(imageUrlList.empty()):
					break
			except urllib2.URLError,e:
				print e.reason
		print ‘文件全部下载完毕...‘

get = getImageUrl()
get.start()
print ‘获取图片链接线程启动:‘

time.sleep(2)

download = getImage()
download.start()
print ‘下载图片链接线程启动:‘
时间: 2024-08-02 06:59:22

Python爬虫之路——简单网页抓图升级版(添加多线程支持)的相关文章

Python爬虫之路——简单网页抓图升级版(增加多线程支持)

转载自我的博客:http://www.mylonly.com/archives/1418.html 经过两个晚上的奋斗,将上一篇文章介绍的爬虫稍微改进了下(Python爬虫之路--简单网页抓图),主要是将获取图片链接任务和下载图片任务用线程分开来处理了,而且这次的爬虫不仅仅可以爬第一页的图片链接的,整个http://desk.zol.com.cn/meinv/下面的图片都会被爬到,而且提供了多种分辨率图片的文件下载,具体设置方法代码注释里面有介绍. 这次的代码仍然有点不足,Ctrl-C无法终止程

Python爬虫之路——简单的网页抓图

转载自我自己的博客:http://www.mylonly.com/archives/1401.html 用Python的urllib2库和HTMLParser库写了一个简单的抓图脚本,主要抓的是http://desk.zol.com.cn/meinv/这个链接下的图片,通过得到图集的起始URL地址,得到第一张图片,然后不断的去获取其下一个图片的URL,继而得到所有首页的图集的图片. 整个源码如下,比较简单,写这个只是简单的练手而已 #coding: utf-8 #################

Python 爬虫修养-处理动态网页

Python 爬虫修养-处理动态网页 本文转自:i春秋社区 0x01 前言 在进行爬虫开发的过程中,我们会遇到很多的棘手的问题,当然对于普通的问题比如 UA 等修改的问题,我们并不在讨论范围,既然要将修养,自然不能说这些完全没有意思的小问题. 0x02 Selenium + PhantomJS 这个东西算是老生长谈的问题吧,基本我在问身边的朋友们的时候,他们都能讲出这条解决方案: Selenium + PhantomJS(Firefox Chrome之类的) 但是真正的有实践过的人,是不会把这个

011 Python 爬虫库安装简单使用

# Python 爬虫基础知识 ● Python 爬虫基础知识 安装爬虫库 beautifulsoup4 pip install beautifulsoup4 lxml HTML 解析器 pip install html5lib html5lib pip install html5lib ● 使用库 设置 encoding='utf-8' 编码 1 # -*- coding: UTF-8 -*- 2 from bs4 import BeautifulSoup 3 import lxml 4 ht

一个咸鱼的Python爬虫之路(三):爬取网页图片

学完Requests库与Beautifulsoup库我们今天来实战一波,爬取网页图片.依照现在所学只能爬取图片在html页面的而不能爬取由JavaScript生成的图.所以我找了这个网站http://www.ivsky.com 网站里面有很多的图集,我们就找你的名字这个图集来爬取 http://www.ivsky.com/bizhi/yourname_v39947/ 来看看这个页面的源代码: 可以看到我们想抓取的图片信息在<li> 里面然后图片地址在img里面那么我们这里可以用Beautifu

Python爬虫学习之获取网页源码

偶然的机会,在知乎上看到一个有关爬虫的话题<利用爬虫技术能做到哪些很酷很有趣很有用的事情?>,因为强烈的好奇心和觉得会写爬虫是一件高大上的事情,所以就对爬虫产生了兴趣. 关于网络爬虫的定义就不多说了,不知道的请自行点击查看 =>百度百科 网络爬虫,维基百科 网络爬虫 有很多编程语言都可以编写网络爬虫,只不过各有各的优缺点,这里我选择用Python语言编写爬虫,因为Python是一门非常适合用来编写爬虫的语言,用它实现爬虫的代码量相对其他语言要少很多,并且python语言对网络编程这类模块

一个咸鱼的python爬虫之路(五):scrapy 爬虫框架

介绍一下scrapy 爬虫框架 安装方法 pip install scrapy 就可以实现安装了.我自己用anaconda 命令为conda install scrapy. 1 Engine从Spider处获得爬取请求(Request)2Engine将爬取请求转发给Scheduler,用于调度 3 Engine从Scheduler处获得下一个要爬取的请求4 Engine将爬取请求通过中间件发送给Downloader5 爬取网页后,Downloader形成响应(Response)通过中间件发给En

Python爬虫实现抓取网页图片

在逛贴吧的时候看见贴吧里面漂亮的图片,或有漂亮妹纸的图片,是不是想保存下来? 但是有的网页的图片比较多,一个个保存下来比较麻烦. 最近在学Python,所以用Python来抓取网页内容还是比较方便的: 所以就尝试了一下 ------code------- #coding=utf-8 import re    import urllib   //导入模块     def gethtml(url):   //自定义函数,传参获取网页内容    page=urllib.urlopen(url)    

python 爬虫之路

想先做个简单的 爬去余弦大大的关注列表 地址:http://www.zhihu.com/people/evilcos/followees 发现不登录无法读取,那么现在先想办法登陆