python多线程图片爬虫

这两天学习python,用python写了一个图片爬虫,顺便学习了一下多线程编程和正则表达式。

上代码:

#!/usr/bin/env python

# Time-stamp: <2013-06-08 00:32:18 Saturday by pein>

# Email: <pein0119@gmail.com>

import re
import urllib
import threading
import time
import Queue


def getHtml(url):
    page = urllib.urlopen(url)
    html = page.read()
    return html


def getUrl(html):
    reg = r"(http://.*?\.jpg!mid)"  #这是根据我要爬的图片写的正则,根据自己情况要改一下
    imgre = re.compile(reg)
    imglist = re.findall(imgre, html)
    return imglist
    
class getImg(threading.Thread):
    """
    """
    
    def __init__(self, q):
        """
        """
        threading.Thread.__init__(self)
        self.q = q
        
    def run(self):   #使用队列实现进程通信
        """
        """
        global count
        while True:
            imgurl = self.q.get()
            # print self.getName()
            urllib.urlretrieve(imgurl, '/home/pein/Pictures/%s.jpg' % count)
            print "%s.jpg done"%count
            count += 1
            if self.q.empty():
                break
            self.q.task_done()
                 
def main():
    """
    """
    global mutex, count
    # url = raw_input("please input a url:\n-->")
    url = "http://girl-atlas.com/a/10130205170100000231"  #要爬的网页地址
    html = getHtml(url)
    imglist = getUrl(html)
    threads = []
    count = 0
    q = Queue.Queue()  #建立消息队列
    
    for i in range(len(imglist)):
        q.put(imglist[i])
    
        
    for i in range(10):
        thread = getImg(q)
        # thread.setName("%s"%i)
        thread.start()
        threads.append(thread)

    for thread in threads:
        thread.join()

main()
推荐一个网站,http://girl-atlas.com/,上面有很多美女写真,写代码写累了,看看美女也是一种放松。

有一点要注意一下:

四十三行             urllib.urlretrieve(imgurl, '/home/pein/Pictures/%s.jpg' % count),这里用的路径是绝对路径,我一开始用了相对路径,后来出错了。

有些东西还不了解,比如说,线程的数量应该不是越多越好,线程创建和启动也是要时间的,所以对于一定量的任务,线程数量应该有个最优值,最优值如何确定?

也许以后会有些头绪。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值