首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python Robotparser超时等效

Python Robotparser超时等效
EN

Stack Overflow用户
提问于 2013-03-06 06:28:32
回答 1查看 539关注 0票数 3

在Python3.3.0中有没有办法设置robotparser.read()函数的超时时间?(例如在urllib.request such打开中)

默认的60秒超时有点太大了。

(我正在自学Python。)

Python 3.3.0 - robotparser

Python 3.3.0 - urllib.request

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-06 06:34:26

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

代码语言:javascript
运行
复制
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())
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15235374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档