urllib.robotparser
--- robots.txt 的剖析器¶
此模組 (module) 提供了一個單獨的類別 (class)RobotFileParser
,它可以知道某個特定 user agent(使用者代理)是否能在有發布robots.txt
文件的網站 fetch(擷取)特定 URL。有關robots.txt
文件結構的更多細節,請參閱http://www.robotstxt.org/orig.html。
- classurllib.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 被允許 fetchurl 的話,則回傳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
類別的基本用法:
>>>importurllib.robotparser>>>rp=urllib.robotparser.RobotFileParser()>>>rp.set_url("http://www.musi-cal.com/robots.txt")>>>rp.read()>>>rrate=rp.request_rate("*")>>>rrate.requests3>>>rrate.seconds20>>>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