天天看點

python爬蟲内置庫之urllib.robotparser--- robots.txt的解析器

此子產品提供單個類,

RobotFileParser

用于回答有關特定使用者代理是否可以在釋出該

robots.txt

檔案的網站上擷取URL的問題。有關

robots.txt

檔案結構的更多詳細資訊,請參閱http://www.robotstxt.org/orig.html。

class 

urllib.robotparser.

RobotFileParser

(url ='' )

此類提供了

robots.txt

在url處讀取,解析和回答有關檔案的問題的方法 。

set_url

(url )

設定引用

robots.txt

檔案的URL 。

read

()

讀取

robots.txt

URL并将其提供給解析器。

parse

(行)

解析線條參數。

can_fetch

(useragent,url )

傳回

True

是否允許useragent 根據解析 檔案中包含的規則擷取url

robots.txt

mtime

()

傳回

robots.txt

上次提取檔案的時間。這對于需要

robots.txt

定期檢查新檔案的長期運作的Web蜘蛛非常有用 。

modified

()

robots.txt

檔案上次提取的時間設定為目前時間。

crawl_delay

(使用者)

傳回有問題 的useragent的

Crawl-delay

參數值。如果沒有此類參數或者它不适用于指定的useragent,或者此參數的條目具有無效文法,則傳回。

robots.txt

robots.txt

None

3.6 新版功能.

request_rate

(使用者)

傳回的内容

Request-rate

從參數 

robots.txt

作為命名的元組 。如果沒有此類參數或者它不适用于 指定的useragent,或者此參數的條目具有無效文法,則傳回。

RequestRate(requests, seconds)

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      

繼續閱讀