urllib.robotparser - Python 中的 robots.txt 解析器
網站所有者使用 /robots.txt 檔案向網路機器人提供有關其網站的說明;這稱為機器人排除協議。此檔案是用於自動訪問 Web 資源的計算機程式的簡單基於文字的訪問控制系統。此類程式稱為蜘蛛、爬蟲等。該檔案指定使用者代理識別符號,後跟代理可能無法訪問的 URL 列表。
例如
#robots.txt Sitemap: https://example.com/sitemap.xml User-agent: * Disallow: /admin/ Disallow: /downloads/ Disallow: /media/ Disallow: /static/
此檔案通常放在 Web 伺服器的頂級目錄中。
Python 的 urllib.robotparser 模組提供了 RobotFileParser 類。它回答有關特定使用者代理是否可以獲取釋出 robots.txt 檔案的網站上的 URL 的問題。
RobotFileParser 類中定義了以下方法
set_url(url)
此方法設定引用 robots.txt 檔案的 URL。
read()
此方法讀取 robots.txt URL 並將其提供給解析器。
parse()
此方法解析 lines 引數。
can_fetch()
如果使用者代理能夠根據 robots.txt 中包含的規則獲取 url,則此方法返回 True。
mtime()
此方法返回上次獲取 robots.txt 檔案的時間。
modified()
此方法設定上次獲取 robots.txt 的時間。
crawl_delay()
此方法返回 robots.txt 中 Crawl-delay 引數的值,該引數適用於使用者代理。
request_rate()
此方法返回 Request-rate 引數的內容,作為命名元組 RequestRate(requests, seconds)。
示例
from urllib import parse from urllib import robotparser AGENT_NAME = 'PyMOTW' URL_BASE = 'https://example.com/' parser = robotparser.RobotFileParser() parser.set_url(parse.urljoin(URL_BASE, 'robots.txt')) parser.read()
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP