urllib.robotparser --- 用于 robots.txt 的解析器¶
源代码: Lib/urllib/robotparser.py
This module provides a single class, RobotFileParser, which answers
questions about whether or not a particular user agent can fetch a URL on the
website that published the robots.txt file. For more details on the
structure of robots.txt files, see http://www.robotstxt.org/orig.html.
- class urllib.robotparser.RobotFileParser(url='')¶
这个类提供了一些可以读取、解析和回答关于 url 上的
robots.txt文件的问题的方法。- set_url(url)¶
设置指向
robots.txt文件的 URL。
- read()¶
读取
robots.txtURL 并将其输入解析器。
- parse(lines)¶
解析行参数。
- can_fetch(useragent, url)¶
如果允许 useragent 按照被解析
robots.txt文件中的规则来获取 url 则返回True。
- mtime()¶
返回最近一次获取
robots.txt文件的时间。 这适用于需要定期检查robots.txt文件更新情况的长时间运行的网页爬虫。
- modified()¶
将最近一次获取
robots.txt文件的时间设置为当前时间。
- crawl_delay(useragent)¶
为指定的 useragent 从
robots.txt返回Crawl-delay形参。 如果此形参不存在或不适用于指定的 useragent 或者此形参的robots.txt条目存在语法错误,则返回None。Added in version 3.6.
- request_rate(useragent)¶
以 named tuple
RequestRate(requests, seconds)的形式从robots.txt返回Request-rate形参的内容。 如果此形参不存在或不适用于指定的 useragent 或者此形参的robots.txt条目存在语法错误,则返回None。Added in version 3.6.
下面的例子演示了 RobotFileParser 类的基本用法:
>>> import urllib.robotparser
>>> rp = urllib.robotparser.RobotFileParser()
>>> rp.set_url("http://www.musi-cal.com/robots.txt")
>>> rp.read()
>>> rrate = rp.request_rate("*")
>>> rrate.requests
3
>>> rrate.seconds
20
>>> rp.crawl_delay("*")
6
>>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco")
False
>>> rp.can_fetch("*", "http://www.musi-cal.com/")
True