1
在Python 3.3.0中有設置robotparser.read()函數超時的方法嗎? (如在urllib.request urlopen中)Python Robotparser超時等效
默認的60秒超時有點激烈。
(我自自學成Python)。
在Python 3.3.0中有設置robotparser.read()函數超時的方法嗎? (如在urllib.request urlopen中)Python Robotparser超時等效
默認的60秒超時有點激烈。
(我自自學成Python)。
不,你必須要麼設置全局默認timout與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 = 60
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())