Copyright (C) 2000 Bastian Kleineidam
You can choose between two licenses when using this package:
2) PSF license for Python 2.2
The robots.txt Exclusion Protocol is implemented as specified in
http://www.robotstxt.org/norobots-rfc.txt
__all__ = ["RobotFileParser"]
""" This class provides a set of methods to read, parse and answer
questions about a single robots.txt file.
def __init__(self, url=''):
self.default_entry = None
self.disallow_all = False
"""Returns the time the robots.txt file was last fetched.
This is useful for long-running web spiders that need to
check for new robots.txt files periodically.
"""Sets the time the robots.txt file was last fetched to the
self.last_checked = time.time()
"""Sets the URL referring to a robots.txt file."""
self.host, self.path = urlparse.urlparse(url)[1:3]
"""Reads the robots.txt URL and feeds it to the parser."""
f = opener.open(self.url)
lines = [line.strip() for line in f]
self.errcode = opener.errcode
if self.errcode in (401, 403):
elif self.errcode >= 400 and self.errcode < 500:
elif self.errcode == 200 and lines:
def _add_entry(self, entry):
if "*" in entry.useragents:
# the default entry is considered last
if self.default_entry is None:
# the first default entry wins
self.default_entry = entry
self.entries.append(entry)
"""parse the input lines from a robots.txt file.
We allow that a user-agent: line is not preceded by
one or more blank lines."""
# 2: saw an allow or disallow line
# remove optional comment and strip line
line = line.split(':', 1)
line[0] = line[0].strip().lower()
line[1] = urllib.unquote(line[1].strip())
if line[0] == "user-agent":
entry.useragents.append(line[1])
elif line[0] == "disallow":
entry.rulelines.append(RuleLine(line[1], False))
entry.rulelines.append(RuleLine(line[1], True))
def can_fetch(self, useragent, url):
"""using the parsed robots.txt decide if useragent can fetch url"""
# Until the robots.txt file has been read or found not
# to exist, we must assume that no url is allowable.
# This prevents false positives when a user erroneously
# calls can_fetch() before calling read().
if not self.last_checked:
# search for given user agent matches
parsed_url = urlparse.urlparse(urllib.unquote(url))
url = urlparse.urlunparse(('', '', parsed_url.path,
parsed_url.params, parsed_url.query, parsed_url.fragment))
for entry in self.entries:
if entry.applies_to(useragent):
return entry.allowance(url)
# try the default entry last
return self.default_entry.allowance(url)
# agent not found ==> access granted
if self.default_entry is not None:
entries = entries + [self.default_entry]
return '\n'.join(map(str, entries)) + '\n'
"""A rule line is a single "Allow:" (allowance==True) or "Disallow:"
(allowance==False) followed by a path."""
def __init__(self, path, allowance):
if path == '' and not allowance:
# an empty value means allow all
path = urlparse.urlunparse(urlparse.urlparse(path))
self.path = urllib.quote(path)
self.allowance = allowance
def applies_to(self, filename):
return self.path == "*" or filename.startswith(self.path)
return (self.allowance and "Allow" or "Disallow") + ": " + self.path
"""An entry has one or more user-agents and zero or more rulelines"""
for agent in self.useragents:
ret.extend(["User-agent: ", agent, "\n"])
for line in self.rulelines:
ret.extend([str(line), "\n"])
def applies_to(self, useragent):
"""check if this entry applies to the specified agent"""
# split the name token and make it lower case
useragent = useragent.split("/")[0].lower()
for agent in self.useragents:
# we have the catch-all agent
def allowance(self, filename):
- our agent applies to this entry
- filename is URL decoded"""
for line in self.rulelines:
if line.applies_to(filename):
class URLopener(urllib.FancyURLopener):
def __init__(self, *args):
urllib.FancyURLopener.__init__(self, *args)
def prompt_user_passwd(self, host, realm):
## If robots.txt file is accessible only with a password,
## we act as if the file wasn't there.
def http_error_default(self, url, fp, errcode, errmsg, headers):
return urllib.FancyURLopener.http_error_default(self, url, fp, errcode,