Python Robotparser 超时等效项
有没有办法在Python 3.3.0中设置robotparser.read()函数的超时时间?(就像在urllib.request的urlopen中那样)
默认的60秒超时时间有点长。
(我正在自学Python。)
1 个回答
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())