urllib.robotparser --- robots.txt 的剖析器¶
此模組提供了一個單獨的類別 RobotFileParser,它可以知道某個特定 user agent(使用者代理)是否能在有發布 robots.txt 文件的網站擷取特定 URL。有關 robots.txt 文件結構的更多細節,請參閱 RFC 9309。
- class urllib.robotparser.RobotFileParser(url='')¶
This class provides methods to read, parse and answer questions about the
robots.txtfile at url or aurllib.request.Requestobject.在 3.16.0a0 (unreleased) 版的變更: url parameter can be a
urllib.request.Requestobject.- set_url(url)¶
Sets the URL referring to a
robots.txtfile or aurllib.request.Requestobject.在 3.16.0a0 (unreleased) 版的變更: url parameter can be a
urllib.request.Requestobject.
- read()¶
讀取
robots.txtURL 並將其輸入到剖析器。
- parse(lines)¶
剖析 lines 引數。
- can_fetch(useragent, url)¶
根據從
robots.txt文件中剖析出的規則,如果 useragent 被允許 fetch url 的話,則回傳True。
- mtime()¶
回傳最近一次 fetch
robots.txt文件的時間。這適用於需要定期檢查robots.txt文件更新情況的長時間運行網頁爬蟲。
- modified()¶
將最近一次 fetch
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.pythontest.net/robots.txt")
>>> rp.read()
>>> rrate = rp.request_rate("*")
>>> rrate.requests
1
>>> rrate.seconds
1
>>> rp.crawl_delay("*")
6
>>> rp.can_fetch("*", "http://www.pythontest.net/")
True
>>> rp.can_fetch("*", "http://www.pythontest.net/no-robots-here/")
False
The following example demonstrates use of a urllib.request.Request
object with additional user-agent headers populated:
>>> import urllib.robotparser
>>> import urllib.request
>>> rp = urllib.robotparser.RobotFileParser()
>>> rp.set_url(urllib.request.Request("http://www.pythontest.net/robots.txt", headers={"User-Agent": "IsraBot"}))
>>> rp.read()
>>> rp.can_fetch("*", "http://www.pythontest.net/")
True
>>> rp.can_fetch("*", "http://www.pythontest.net/no-robots-here/")
False