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.txt
URL 並將其提供給解析器。
- parse(lines)¶
解析 lines 引數。
- can_fetch(useragent, url)¶
如果根據已解析的
robots.txt
檔案中包含的規則,允許 useragent 獲取 url,則返回True
。
- mtime()¶
返回上次獲取
robots.txt
檔案的時間。 這對於需要定期檢查新的robots.txt
檔案的長時間執行的網路爬蟲很有用。
- modified()¶
將上次獲取
robots.txt
檔案的時間設定為當前時間。
- crawl_delay(useragent)¶
從
robots.txt
中返回所討論的 useragent 的Crawl-delay
引數的值。 如果沒有這樣的引數,或者它不適用於指定的 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