Python Robotparser 超时等效项

Ter*_*nce 3 python robots.txt python-3.x

Python 3.3.0 有没有办法设置 robotsparser.read() 函数的超时时间?(比如在 urllib.request urlopen 中)

60 秒的默认超时时间有点过分。

(我正在自学 Python。)

Python 3.3.0 - 机器人解析器

Python 3.3.0 - urllib.request

Mar*_*ers 6

不,您必须使用 设置全局默认超时socket.setdefaulttimeout(),或者将RobotFileParser类子类化以添加自定义超时:

from urllib.robotparser import RobotFileParser
import urllib.request

class TimoutRobotFileParser(RobotFileParser):
    def __init__(self, url='', timeout=60):
        super().__init__(url)
        self.timeout = timeout

    def read(self):
        """Reads the robots.txt URL and feeds it to the parser."""
        try:
            f = urllib.request.urlopen(self.url, timeout=self.timeout)
        except urllib.error.HTTPError as err:
            if err.code in (401, 403):
                self.disallow_all = True
            elif err.code >= 400:
                self.allow_all = True
        else:
            raw = f.read()
            self.parse(raw.decode("utf-8").splitlines())
Run Code Online (Sandbox Code Playgroud)