免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1789 | 回复: 1
打印 上一主题 下一主题

一个多线程爬虫问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-05-26 22:08 |只看该作者 |倒序浏览
这段代码爬链接少的,可以正常返回,但爬链接多一些的,就返回不了了
不知道哪写错了,求教~

Python code

# coding:utf-8

import threading
import urllib
from Queue import Queue
from BeautifulSoup import BeautifulSoup
import re

class Worker(threading.Thread):
    """ thread pool class """
    def __init__(self, queue, deep, empty_urls):
        super(Worker, self).__init__()
        self.queue = queue
        self.deep = deep
        self.urls_list = empty_urls

    def getpage(self, urltuple):
        """ 得到一个页面的所有链接 """
        level, url = urltuple
        try:
            page = urllib.urlopen(url).read()
        except UnicodeEncodeError, uee:
            page = urllib.urlopen(url.encode("utf-8").read()
            print uee
            return None
        except IOError, ioe:
            print ioe
            return None
        except Exception:
            return None
        if level >= self.deep:
            return page
        try:
            soup = BeautifulSoup(page)
        except:
            print "抓取错误", url
            return None
        # print soup
        urlall = soup.findAll('a', onclick=None, href=re.compile('^http^/'))
        if url.endswith('/'):
            url = url[:-1]

        url = "http://www.baidu.com"

        for i in urlall:
            if i['href'].startswith('/'):
                i['href'] = url + i['href']

            self.urls_list.lock()
            if i['href'] not in self.urls_list.urls:
                self.urls_list.urls.append(i['href'])
                self.queue.put((level+1, i['href']))
            self.urls_list.release()
        return page

    def run(self):
        while True:
            urltuple = self.queue.get()
            #self.log.write(urltuple[1])
            try:
                print urltuple[1]
            except UnicodeEncodeError, uee:
                print uee
                print urltuple[1].encode("UTF-8"
            page = self.getpage(urltuple)

            self.queue.task_done()

class EmptyUrl(object):
    """docstring for EmptyUrl"""
    def __init__(self):
        super(EmptyUrl, self).__init__()
        self.urls = []
        self.mutex = threading.Lock()

    def lock(self):
        """ get_lock """
        self.mutex.acquire()

    def release(self):
        """ release """
        self.mutex.release()


def main():
    """ start """
    queue = Queue(0)
    i = 0

    url = "http://www.baidu.com/"
    queue.put((0, url))
   
    urls = EmptyUrl()
    urls.urls.append(url)

    while i < 50:
        work = Worker(queue, 2, urls)
        work.setDaemon(True)
        work.start()  
        i += 1  

    queue.join()

if __name__ == '__main__':
    main()

论坛徽章:
0
2 [报告]
发表于 2012-07-13 09:34 |只看该作者
代码放到代码标签里
可以自己加些print代码来看看执行到哪里会停止
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP