urllib.robotparser - Python 中的 robots.txt 解析器


网站所有者使用 /robots.txt 文件向网络机器人提供有关其网站的说明;这称为机器人排除协议。此文件是用于自动访问 Web 资源的计算机程序的简单基于文本的访问控制系统。此类程序称为蜘蛛、爬虫等。该文件指定用户代理标识符,后跟代理可能无法访问的 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。

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

read()

此方法读取 robots.txt URL 并将其提供给解析器。

parse()

此方法解析 lines 参数。

can_fetch()

如果用户代理能够根据 robots.txt 中包含的规则获取 url,则此方法返回 True。

mtime()

此方法返回上次获取 robots.txt 文件的时间。

modified()

此方法设置上次获取 robots.txt 的时间。

crawl_delay()

此方法返回 robots.txt 中 Crawl-delay 参数的值,该参数适用于用户代理。

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()

更新于: 2019-07-30

561 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告