urllib.robotparser - Python 中的 robots.txt 解析器
pythonserver side programmingprogramming更新于 2025/5/29 12:28:17
网站所有者使用 /robots.txt 文件向网络机器人提供有关其网站的指令;这称为"机器人排除协议"。此文件是一个简单的基于文本的访问控制系统,用于自动访问网络资源的计算机程序。此类程序称为蜘蛛、爬虫等。该文件指定用户代理标识符,后跟代理不得访问的 URL 列表。
例如
#robots.txt Sitemap: https://example.com/sitemap.xml User-agent: * Disallow: /admin/ Disallow: /downloads/ Disallow: /media/ Disallow: /static/
此文件通常放在 Web 服务器的顶级目录中。
Python 的 urllib.robotparser 模块提供了 RobotFileParser 类。它回答了有关特定用户代理是否可以在发布 robots.txt 文件的网站上获取 URL 的问题。
以下方法在 RobotFileParser 类中定义
set_url(url)
此方法设置引用 robots.txt 文件的 URL。
read()
此方法读取 robots.txt URL 并将其提供给解析器。
parse()
此方法解析 lines 参数。
can_fetch()
如果用户代理能够根据 robots.txt 中包含的规则获取 url,则此方法返回 True。
mtime()
此方法返回 robots.txt 文件上次被访问的时间已获取。
modified()
此方法设置 robots.txt 上次获取的时间。
crawl_delay()
此方法返回相关用户代理的 Crawl-delay 参数 robots.txt 的值。
request_rate()
此方法将 Request-rate 参数的内容作为命名元组 RequestRate(requests, seconds) 返回。
示例
from urllib import parse from urllib import robotparser AGENT_NAME = 'PyMOTW' URL_BASE = 'https://example.com/' parser = robotparser.RobotFileParser() parser.set_url(parse.urljoin(URL_BASE, 'robots.txt')) parser.read()
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

