美文网首页Python爬虫
人生不得已——Python爬虫 限速

人生不得已——Python爬虫 限速

作者: 阿猫阿狗py | 来源:发表于2018-11-03 16:39 被阅读24次

下载限速

如果我们爬取网站的速度过快,就会面临被 封禁或是造成服务器过载的风险。
为了降低这些风险, 我们可以在两次下载之间添加延时,从而对爬虫限速。

方法: Throttle 类记录了每个域名上次访问的时间,如果当前时间距离上次
访问时间小于指定延时,则执行睡眠操作。 我们可以在每次下载之前调用
Throttle 对爬虫进行限速。

Throttle 类的实现

import urllib.parse
import time
import datetime
import re
import urllib.request


class Throttle:

    def __init__(self, delay):
        # 访问同域名时需要的间隔时间
        self.delay = delay
        # key:netloc,value:lastTime.记录每个域名的上一次访问的时间戳
        self.domains = {}

    # 计算需要的等待时间,并执行等待
    def wait(self, url):
        if self.delay <= 0:
            print('delay ='+self.delay)
            return

        domain = urllib.parse.urlparse(url).netloc
        lastTime = self.domains.get(domain)

        if lastTime is not None:
            # 计算等待时间
            wait_sec = self.delay - (datetime.datetime.now() - lastTime).seconds
            if wait_sec > 0:
                time.sleep(wait_sec)

        self.domains[domain] = datetime.datetime.now()

使用方式

在爬虫函数中

t = Throttle(0.5)

#在循环内
t.wait(url)

相关文章

网友评论

    本文标题:人生不得已——Python爬虫 限速

    本文链接:https://www.haomeiwen.com/subject/yhnkxqtx.html