urllib.robotparser --- robots.txt è¯æ³•分æž�程åº�¶
æº�代ç �: Lib/urllib/robotparser.py
æ¤æ¨¡å�—æ��供了一个å�•独的类 RobotFileParser,它å�¯ä»¥å›žç”关于æŸ�个特定用户代ç�†èƒ½å�¦åœ¨å�‘布了 robots.txt 文件的网站抓å�–特定 URL 的问题。 有关 robots.txt 文件结构的更多细节,请å�‚阅 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。在 3.6 ç‰ˆæœ¬åŠ å…¥.
- request_rate(useragent)¶
以 named tuple
RequestRate(requests, seconds)的形å¼�从robots.txt返回Request-rateå½¢å�‚的内容。 如果æ¤å½¢å�‚ä¸�å˜åœ¨æˆ–ä¸�适用于指定的 useragent 或者æ¤å½¢å�‚çš„robots.txtæ�¡ç›®å˜åœ¨è¯æ³•错误,则返回None。在 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