blob: 1722863d144db7fc1956292892ebf49dc3f0cd3a [file] [log] [blame]
Skip Montanaro663f6c22001-01-20 15:59:25 +00001""" robotparser.py
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +00002
Skip Montanaro663f6c22001-01-20 15:59:25 +00003 Copyright (C) 2000 Bastian Kleineidam
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +00004
Skip Montanaro663f6c22001-01-20 15:59:25 +00005 You can choose between two licenses when using this package:
6 1) GNU GPLv2
Martin v. Löwisd22368f2002-03-18 10:41:20 +00007 2) PSF license for Python 2.2
Skip Montanaro663f6c22001-01-20 15:59:25 +00008
9 The robots.txt Exclusion Protocol is implemented as specified in
10 http://info.webcrawler.com/mak/projects/robots/norobots-rfc.html
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +000011"""
Skip Montanarob8bdbc02008-04-28 03:27:53 +000012import urlparse
13import urllib
Skip Montanaro663f6c22001-01-20 15:59:25 +000014
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000015__all__ = ["RobotFileParser"]
16
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +000017
18class RobotFileParser:
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000019 """ This class provides a set of methods to read, parse and answer
20 questions about a single robots.txt file.
21
22 """
23
Skip Montanaro663f6c22001-01-20 15:59:25 +000024 def __init__(self, url=''):
25 self.entries = []
Martin v. Löwis1c63f6e2002-02-28 15:24:47 +000026 self.default_entry = None
Martin v. Löwis31bd5292004-08-23 20:42:35 +000027 self.disallow_all = False
28 self.allow_all = False
Skip Montanaro663f6c22001-01-20 15:59:25 +000029 self.set_url(url)
Guido van Rossum986abac1998-04-06 14:29:28 +000030 self.last_checked = 0
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +000031
32 def mtime(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000033 """Returns the time the robots.txt file was last fetched.
34
35 This is useful for long-running web spiders that need to
36 check for new robots.txt files periodically.
37
38 """
Guido van Rossum986abac1998-04-06 14:29:28 +000039 return self.last_checked
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +000040
41 def modified(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000042 """Sets the time the robots.txt file was last fetched to the
43 current time.
44
45 """
Guido van Rossum986abac1998-04-06 14:29:28 +000046 import time
47 self.last_checked = time.time()
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +000048
49 def set_url(self, url):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000050 """Sets the URL referring to a robots.txt file."""
Guido van Rossum986abac1998-04-06 14:29:28 +000051 self.url = url
Skip Montanaro663f6c22001-01-20 15:59:25 +000052 self.host, self.path = urlparse.urlparse(url)[1:3]
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +000053
54 def read(self):
Raymond Hettingeraef22fb2002-05-29 16:18:42 +000055 """Reads the robots.txt URL and feeds it to the parser."""
Skip Montanaro5bba2312001-02-12 20:58:30 +000056 opener = URLopener()
57 f = opener.open(self.url)
Benjamin Peterson0522a9f2008-07-12 23:41:19 +000058 lines = [line.strip() for line in f]
59 f.close()
Skip Montanaro5bba2312001-02-12 20:58:30 +000060 self.errcode = opener.errcode
Georg Brandl4ffc8f52007-03-13 09:41:31 +000061 if self.errcode in (401, 403):
Martin v. Löwis31bd5292004-08-23 20:42:35 +000062 self.disallow_all = True
Skip Montanaro5bba2312001-02-12 20:58:30 +000063 elif self.errcode >= 400:
Martin v. Löwis31bd5292004-08-23 20:42:35 +000064 self.allow_all = True
Skip Montanaro5bba2312001-02-12 20:58:30 +000065 elif self.errcode == 200 and lines:
Skip Montanaro5bba2312001-02-12 20:58:30 +000066 self.parse(lines)
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +000067
Martin v. Löwis73f570b2002-03-18 10:43:18 +000068 def _add_entry(self, entry):
69 if "*" in entry.useragents:
70 # the default entry is considered last
Georg Brandl2bd953e2010-08-01 20:59:03 +000071 if self.default_entry is None:
72 # the first default entry wins
73 self.default_entry = entry
Martin v. Löwis73f570b2002-03-18 10:43:18 +000074 else:
75 self.entries.append(entry)
76
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +000077 def parse(self, lines):
Raymond Hettinger2d95f1a2004-03-13 20:27:23 +000078 """parse the input lines from a robots.txt file.
Tim Petersdfc538a2001-01-21 04:49:16 +000079 We allow that a user-agent: line is not preceded by
80 one or more blank lines."""
Skip Montanaro1ef19f02008-07-27 00:49:02 +000081 # states:
82 # 0: start state
83 # 1: saw user-agent line
84 # 2: saw an allow or disallow line
Skip Montanaro663f6c22001-01-20 15:59:25 +000085 state = 0
86 linenumber = 0
87 entry = Entry()
Tim Petersdfc538a2001-01-21 04:49:16 +000088
Guido van Rossum986abac1998-04-06 14:29:28 +000089 for line in lines:
Benjamin Peterson0522a9f2008-07-12 23:41:19 +000090 linenumber += 1
Skip Montanaro663f6c22001-01-20 15:59:25 +000091 if not line:
Skip Montanarob8bdbc02008-04-28 03:27:53 +000092 if state == 1:
Skip Montanaro663f6c22001-01-20 15:59:25 +000093 entry = Entry()
94 state = 0
Skip Montanarob8bdbc02008-04-28 03:27:53 +000095 elif state == 2:
Martin v. Löwis73f570b2002-03-18 10:43:18 +000096 self._add_entry(entry)
Skip Montanaro663f6c22001-01-20 15:59:25 +000097 entry = Entry()
98 state = 0
Guido van Rossum986abac1998-04-06 14:29:28 +000099 # remove optional comment and strip line
Eric S. Raymond141971f2001-02-09 08:40:40 +0000100 i = line.find('#')
Skip Montanarob8bdbc02008-04-28 03:27:53 +0000101 if i >= 0:
Skip Montanaro663f6c22001-01-20 15:59:25 +0000102 line = line[:i]
Eric S. Raymond141971f2001-02-09 08:40:40 +0000103 line = line.strip()
Guido van Rossum986abac1998-04-06 14:29:28 +0000104 if not line:
105 continue
Eric S. Raymond141971f2001-02-09 08:40:40 +0000106 line = line.split(':', 1)
Guido van Rossum986abac1998-04-06 14:29:28 +0000107 if len(line) == 2:
Eric S. Raymond141971f2001-02-09 08:40:40 +0000108 line[0] = line[0].strip().lower()
Martin v. Löwis1c63f6e2002-02-28 15:24:47 +0000109 line[1] = urllib.unquote(line[1].strip())
Skip Montanaro663f6c22001-01-20 15:59:25 +0000110 if line[0] == "user-agent":
Skip Montanarob8bdbc02008-04-28 03:27:53 +0000111 if state == 2:
Martin v. Löwis73f570b2002-03-18 10:43:18 +0000112 self._add_entry(entry)
Skip Montanaro663f6c22001-01-20 15:59:25 +0000113 entry = Entry()
114 entry.useragents.append(line[1])
115 state = 1
116 elif line[0] == "disallow":
Skip Montanarob8bdbc02008-04-28 03:27:53 +0000117 if state != 0:
Martin v. Löwis31bd5292004-08-23 20:42:35 +0000118 entry.rulelines.append(RuleLine(line[1], False))
Skip Montanaro663f6c22001-01-20 15:59:25 +0000119 state = 2
120 elif line[0] == "allow":
Skip Montanarob8bdbc02008-04-28 03:27:53 +0000121 if state != 0:
Martin v. Löwis31bd5292004-08-23 20:42:35 +0000122 entry.rulelines.append(RuleLine(line[1], True))
Skip Montanaro1ef19f02008-07-27 00:49:02 +0000123 state = 2
Skip Montanarob8bdbc02008-04-28 03:27:53 +0000124 if state == 2:
Georg Brandl2bd953e2010-08-01 20:59:03 +0000125 self._add_entry(entry)
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +0000126
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +0000127
Guido van Rossumdc8b7982000-03-27 19:29:31 +0000128 def can_fetch(self, useragent, url):
129 """using the parsed robots.txt decide if useragent can fetch url"""
Skip Montanaro663f6c22001-01-20 15:59:25 +0000130 if self.disallow_all:
Tim Petersbc0e9102002-04-04 22:55:58 +0000131 return False
Skip Montanaro663f6c22001-01-20 15:59:25 +0000132 if self.allow_all:
Tim Petersbc0e9102002-04-04 22:55:58 +0000133 return True
Skip Montanaro663f6c22001-01-20 15:59:25 +0000134 # search for given user agent matches
135 # the first match counts
Senthil Kumarana4f79f92010-07-28 16:35:35 +0000136 parsed_url = urlparse.urlparse(urllib.unquote(url))
137 url = urlparse.urlunparse(('', '', parsed_url.path,
138 parsed_url.params, parsed_url.query, parsed_url.fragment))
139 url = urllib.quote(url)
140 if not url:
141 url = "/"
Skip Montanaro663f6c22001-01-20 15:59:25 +0000142 for entry in self.entries:
143 if entry.applies_to(useragent):
144 return entry.allowance(url)
Martin v. Löwis1c63f6e2002-02-28 15:24:47 +0000145 # try the default entry last
146 if self.default_entry:
147 return self.default_entry.allowance(url)
Skip Montanaro663f6c22001-01-20 15:59:25 +0000148 # agent not found ==> access granted
Tim Petersbc0e9102002-04-04 22:55:58 +0000149 return True
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +0000150
Guido van Rossumbbf8c2f1997-01-30 03:18:23 +0000151
Skip Montanaro663f6c22001-01-20 15:59:25 +0000152 def __str__(self):
Georg Brandl4ffc8f52007-03-13 09:41:31 +0000153 return ''.join([str(entry) + "\n" for entry in self.entries])
Skip Montanaro663f6c22001-01-20 15:59:25 +0000154
155
156class RuleLine:
Martin v. Löwis31bd5292004-08-23 20:42:35 +0000157 """A rule line is a single "Allow:" (allowance==True) or "Disallow:"
158 (allowance==False) followed by a path."""
Skip Montanaro663f6c22001-01-20 15:59:25 +0000159 def __init__(self, path, allowance):
Martin v. Löwis1c63f6e2002-02-28 15:24:47 +0000160 if path == '' and not allowance:
161 # an empty value means allow all
Martin v. Löwis31bd5292004-08-23 20:42:35 +0000162 allowance = True
Skip Montanaro663f6c22001-01-20 15:59:25 +0000163 self.path = urllib.quote(path)
164 self.allowance = allowance
165
166 def applies_to(self, filename):
Skip Montanarob8bdbc02008-04-28 03:27:53 +0000167 return self.path == "*" or filename.startswith(self.path)
Skip Montanaro663f6c22001-01-20 15:59:25 +0000168
169 def __str__(self):
Skip Montanarob8bdbc02008-04-28 03:27:53 +0000170 return (self.allowance and "Allow" or "Disallow") + ": " + self.path
Skip Montanaro663f6c22001-01-20 15:59:25 +0000171
172
173class Entry:
174 """An entry has one or more user-agents and zero or more rulelines"""
175 def __init__(self):
176 self.useragents = []
177 self.rulelines = []
178
179 def __str__(self):
Georg Brandl4ffc8f52007-03-13 09:41:31 +0000180 ret = []
Skip Montanaro663f6c22001-01-20 15:59:25 +0000181 for agent in self.useragents:
Georg Brandl4ffc8f52007-03-13 09:41:31 +0000182 ret.extend(["User-agent: ", agent, "\n"])
Skip Montanaro663f6c22001-01-20 15:59:25 +0000183 for line in self.rulelines:
Georg Brandl4ffc8f52007-03-13 09:41:31 +0000184 ret.extend([str(line), "\n"])
185 return ''.join(ret)
Skip Montanaro663f6c22001-01-20 15:59:25 +0000186
187 def applies_to(self, useragent):
Skip Montanaro5bba2312001-02-12 20:58:30 +0000188 """check if this entry applies to the specified agent"""
189 # split the name token and make it lower case
190 useragent = useragent.split("/")[0].lower()
Skip Montanaro663f6c22001-01-20 15:59:25 +0000191 for agent in self.useragents:
Skip Montanarob8bdbc02008-04-28 03:27:53 +0000192 if agent == '*':
Skip Montanaro5bba2312001-02-12 20:58:30 +0000193 # we have the catch-all agent
Tim Petersbc0e9102002-04-04 22:55:58 +0000194 return True
Skip Montanaro5bba2312001-02-12 20:58:30 +0000195 agent = agent.lower()
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000196 if agent in useragent:
Tim Petersbc0e9102002-04-04 22:55:58 +0000197 return True
198 return False
Skip Montanaro663f6c22001-01-20 15:59:25 +0000199
200 def allowance(self, filename):
201 """Preconditions:
202 - our agent applies to this entry
203 - filename is URL decoded"""
204 for line in self.rulelines:
205 if line.applies_to(filename):
206 return line.allowance
Martin v. Löwis31bd5292004-08-23 20:42:35 +0000207 return True
Skip Montanaro663f6c22001-01-20 15:59:25 +0000208
Skip Montanaro5bba2312001-02-12 20:58:30 +0000209class URLopener(urllib.FancyURLopener):
210 def __init__(self, *args):
Guido van Rossum68468eb2003-02-27 20:14:51 +0000211 urllib.FancyURLopener.__init__(self, *args)
Skip Montanaro5bba2312001-02-12 20:58:30 +0000212 self.errcode = 200
Tim Peters0e6d2132001-02-15 23:56:39 +0000213
Skip Montanaro1a413132007-08-28 23:22:52 +0000214 def prompt_user_passwd(self, host, realm):
215 ## If robots.txt file is accessible only with a password,
216 ## we act as if the file wasn't there.
217 return None, None
218
Skip Montanaro5bba2312001-02-12 20:58:30 +0000219 def http_error_default(self, url, fp, errcode, errmsg, headers):
220 self.errcode = errcode
221 return urllib.FancyURLopener.http_error_default(self, url, fp, errcode,
222 errmsg, headers)