对爬取整站进行多线程优化

上一篇聊的爬整站的例子上,爬虫的动力主要是依靠一个同步的循环体,很明显,就行进速度来说,它太慢了。雪上加霜的是在我这个地区,访问示例中的目标网站的速度还很不理想。因此我想把他改进一下。

改进思路

通过分析,发现影响速度的主要是两个方面:

  1. cache 队列太长,每次只能消化一个元素
  2. 网络访问速度慢

网络访问速度可以通过加代理来解决,不过这个不是我们这次要聊的主题。我们着重分析一下如何提升cache队列的消化速度。如图所示,之前的例子中每次只能消化一个元素,而且还是得在消化完之后才论到下一个。我希望的是——队列中只要一有元素,马上开始处理。这个场景中,我不需要等待它为我返回处理结果,因为它自会把处理结果put进相应的队列中。

处理流程

先看看伪码的实现

def 爬取(url):
    html = 访问(url)
    for td in html:
        if 在<td>中找到了<span class="octicon octicon-file-directory">:
            cache.入队(td.url)
        elif 在<td>中找到了<span class="octicon octicon-file-text">:
            处理爬取成果

while:
    url = 首元素出队
    if 超时返回:
        已经爬完整站,退出循环
    启动新线程(爬取(url))

完整代码

from bs4 import BeautifulSoup
import requests
import threading
import time

class LQueue:
    def __init__(self):
        self._queue = []
        self.mutex = threading.Lock()
        self.condition = threading.Condition(self.mutex)

    def put(self, item):
        with self.condition:
            self._queue.append(item)
            self.condition.notify()

    def get_nowait(self):
        if not self.empty():
            return self._queue.pop(0)
        else:
            raise IndexError('Empty Queue')
    
    def get(self, timeout=60):
        with self.condition:
            endtime = time.time() + timeout
            while True:
                if not self.empty():
                    return self._queue.pop(0)
                else:
                    remaining = endtime - time.time()
                    if remaining <= 0.0:
                        return None
                    self.condition.wait(remaining)

    def has(self, item):
        if item in self._queue:
            return True
        else:
            return False

    def empty(self):
        if self._queue.__len__() == 0:
            return True
        else:
            return False

def find_links(url, queue):
    print('Accessing:{}'.format(url))
    headers = {
        'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5'
    }
    try:
        html = requests.get(url, headers=headers, timeout=30)
        html.raise_for_status
        html.encoding = html.apparent_encoding
    except:
        return
    soup = BeautifulSoup(html.text, "html.parser")
    tds = soup.find('tbody').find_all('td', class_='name four wide')
    for td in tds:
        if td.find('span', class_='octicon octicon-file-directory') is not None:
            # directory enqueue 'cache'
            href = 'https://opendev.org' + td.find('a')['href']
            if not queue.has(href):
                queue.put(href)
        elif td.find('span', class_='octicon octicon-file-text') is not None:
            href = 'https://opendev.org' + td.find('a')['href']
            # 处理爬取成果

cache = LQueue()
link = 'https://opendev.org/openstack/neutron'
cache.put(link)

while True:
    url = cache.get(35)
    if url is None:
        break
    threading.Thread(target=find_links, args=(url, cache)).start()

这时候你可以跑一下,体会那种充分利用计算机资源的感觉。不过在这段代码里,我没有写对爬取成果处理的部分。因为我想介绍一个有意思的东西——任务队列。在这个场景中,它跟多线程的作用差不多,但它真正的意义在于能帮我把任务分发到其他机器上去执行,类似的好处还有使用“订阅-发布”让多台机器帮你一起干等等。至于分发什么任务,这就随心所欲了。比如把所有URL成果放进数据库里,再设计一个定时任务,让它每过一会帮你做一次去重操作。
我用的是RQ(RedisQueue),一个很轻量级的 python 任务队列库,RQ 的工作依赖于Redis,并且需要 Redis版本 >= 3.0.0.。我已经安装过了,直接运行。

$ redis-server 
image.png

注意:由于我是本地运行、使用,因此Redis侦听localhost:6379,并且我连接它的时候也不需要安全验证。如果你是在不同的机器上,需要合理的修改配置文件。

接着安装rq库

$ pip3 install rq

增加实现 rq 的代码

...
import rq
from redis import Redis

class LQueue:
    ...

def find_links(url, queue, task_queue):
    ...
        elif td.find('span', class_='octicon octicon-file-text') is not None:
            # 把爬取成果发送到任务队列,让 'process_result' 去处理
            href = 'https://opendev.org' + td.find('a')['href']
            task_queue.enqueue('tasks.process_result', href)

...
cache.put(link)
# 创建任务队列对象,绑定到名叫 'task1' 的worker上
task_queue1 = rq.Queue('task1', connection=Redis.from_url('redis://'))

while True:
    url = cache.get(35)
    if url is None:
        break
    threading.Thread(target=find_links, args=(url, cache, task_queue1)).start()

任务队列里有个worker的概念,当我使用obj.enqueue()把任务送进队列之后,worker正这个任务的执行者。即然是交给人家任务,那就得告诉人家怎么干,如果需要加工原材料,那原材料也得一并提供。例如我把一张原始表单发给助理,告诉她明天下班之前按预定模板整理成报表并邮件发送给张三抄给我。助理就是worker。在task_queue.enqueue('tasks.process_result', href)中,'tasks.process_result'是任务描述,href是原始表单。多个worker可以同时绑定到一个队列上,就好比我有多个助理,他们同时帮我干一件事。每个worker也可以分别绑到不同的队列上,就像我把不同的任务交给不同的助理。

两个worker绑到一个队列上

在工作目录下创建文件tasks.py,并添加任务处理代码。我尽量言简意赅,保持页面清爽,就直接print了,想像留给你。

def process_result(href):
    print(href)

接着开启一个新的终端窗口,进入到工作目录,启动一个worker

rqworker task1
worker

再试着跑一下,看看worker的控制台是不是像我的一样输出的url内容。

限制并发访问数量

如果一直停留在访问初始连接的字样上,很有可能是刚刚开启的线程数量太大,导致目标站服务器让你“冷静一会”。这时候尝试用浏览器再访问一下初始URL,如果一直连接不成功,就可以确认结果了。
说实话我是非常喜欢那种简单粗爆直接硬来的畅快感,像不堵车的五环一脚油到底。可目标站显然承受不了这种过量的连接。工具在给我们带来便利的同时,它也产生了一定的危害。说到底,关键在于利刃作什么用。切记要在合理合法的范围内收集信息。
像上面的例子实际来说是不可取的,也行不通。我准备再次优化一下,限制它并发访问的数量。

还是先来看看伪码的实现

def 爬取(url):
    html = 访问(url)
    for td in html:
        if 在<td>中找到了<span class="octicon octicon-file-directory">:
            cache.入队(td.url)
        elif 在<td>中找到了<span class="octicon octicon-file-text">:
            处理爬取成果
    唤醒因数量过载而被阻塞的线程

while 队列不为空:
    url = 首元素出队
    if url is None:
        已经爬完整站,退出循环
    if 计数器过载
        等待运行中的线程执行完毕后唤醒我
        计数器 ++
    多线程爬取(url)
    计数器 -- 

增加限制和唤醒线程的代码

class LQueue:
   ...

def find_links(url, queue, task_queue, condition):
    print('Accessing:{}'.format(url))
    headers = {
        'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5'
    }
    try:
        html = requests.get(url, headers=headers, timeout=30)
        html.raise_for_status
        html.encoding = html.apparent_encoding
    except:
        with condition:
            # 异常情况下的唤醒
            condition.notify()
            return 
    soup = BeautifulSoup(html.text, "html.parser")
    tds = soup.find('tbody').find_all('td', class_='name four wide')
    for td in tds:
        if td.find('span', class_='octicon octicon-file-directory') is not None:
            # directory enqueue 'cache'
            href = 'https://opendev.org' + td.find('a')['href']
            if not queue.has(href):
                queue.put(href)
        elif td.find('span', class_='octicon octicon-file-text') is not None:
            # send to task queue
            href = 'https://opendev.org' + td.find('a')['href']
            task_queue.enqueue('tasks.process_result', href)
    with condition:
        # 正常执行完毕后的唤醒
        condition.notify()

cache = LQueue()
link = 'https://opendev.org/openstack/neutron'
cache.put(link)
task_queue1 = rq.Queue('task1', connection=Redis.from_url('redis://'))

condition = threading.Condition(threading.Lock())
# 最多同时开启线程
counter = 5

while True:
    url = cache.get(35)
    if url is None:
        break
    if counter <= 0:
        with condition:
            condition.wait()
            counter = counter + 1
    threading.Thread(target=find_links, args=(url, cache, task_queue1, condition)).start()
    counter = counter - 1
        
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335