Debian Codegraph @

Lib/urllib/robotparser.py

raw
1 """ robotparser.py
2
3 Copyright (C) 2000 Bastian Kleineidam
4
5 You can choose between two licenses when using this package:
6 1) GNU GPLv2
7 2) PSF license for Python 2.2
8
9 The robots.txt Exclusion Protocol is implemented as specified in
10 http://www.robotstxt.org/norobots-rfc.txt
11 """
12
13 import collections
14 import re
15 import urllib.error
16 import urllib.parse
17 import urllib.request
18
19 __all__ = ["RobotFileParser"]
20
21 RequestRate = collections.namedtuple("RequestRate", "requests seconds")
22
23
24 def normalize(path):
25 unquoted = urllib.parse.unquote(path, errors='surrogateescape')
26 return urllib.parse.quote(unquoted, errors='surrogateescape')
27
28 def normalize_path(path):
29 path, sep, query = path.partition('?')
30 path = normalize(path)
31 if sep:
32 query = re.sub(r'[^=&]+', lambda m: normalize(m[0]), query)
33 path += '?' + query
34 return path
35
36
37 class RobotFileParser:
38 """ This class provides a set of methods to read, parse and answer
39 questions about a single robots.txt file.
40
41 """
42
43 def __init__(self, url=''):
44 self.entries = []
45 self.sitemaps = []
46 self.default_entry = None
47 self.disallow_all = False
48 self.allow_all = False
49 self.set_url(url)
50 self.last_checked = 0
51
52 def mtime(self):
53 """Returns the time the robots.txt file was last fetched.
54
55 This is useful for long-running web spiders that need to
56 check for new robots.txt files periodically.
57
58 """
59 return self.last_checked
60
61 def modified(self):
62 """Sets the time the robots.txt file was last fetched to the
63 current time.
64
65 """
66 import time
67 self.last_checked = time.time()
68
69 def set_url(self, url):
70 """Sets the URL referring to a robots.txt file."""
71 self.url = url
72 self.host, self.path = urllib.parse.urlsplit(url)[1:3]
73
74 def read(self):
75 """Reads the robots.txt URL and feeds it to the parser."""
76 try:
77 f = urllib.request.urlopen(self.url)
78 except urllib.error.HTTPError as err:
79 if err.code in (401, 403):
80 self.disallow_all = True
81 elif err.code >= 400 and err.code < 500:
82 self.allow_all = True
83 err.close()
84 else:
85 raw = f.read()
86 self.parse(raw.decode("utf-8", "surrogateescape").splitlines())
87
88 def _add_entry(self, entry):
89 if "*" in entry.useragents:
90 # the default entry is considered last
91 if self.default_entry is None:
92 # the first default entry wins
93 self.default_entry = entry
94 else:
95 self.entries.append(entry)
96
97 def parse(self, lines):
98 """Parse the input lines from a robots.txt file.
99
100 We allow that a user-agent: line is not preceded by
101 one or more blank lines.
102 """
103 # states:
104 # 0: start state
105 # 1: saw user-agent line
106 # 2: saw an allow or disallow line
107 state = 0
108 entry = Entry()
109
110 self.modified()
111 for line in lines:
112 if not line:
113 if state == 1:
114 entry = Entry()
115 state = 0
116 elif state == 2:
117 self._add_entry(entry)
118 entry = Entry()
119 state = 0
120 # remove optional comment and strip line
121 i = line.find('#')
122 if i >= 0:
123 line = line[:i]
124 line = line.strip()
125 if not line:
126 continue
127 line = line.split(':', 1)
128 if len(line) == 2:
129 line[0] = line[0].strip().lower()
130 line[1] = line[1].strip()
131 if line[0] == "user-agent":
132 if state == 2:
133 self._add_entry(entry)
134 entry = Entry()
135 entry.useragents.append(line[1])
136 state = 1
137 elif line[0] == "disallow":
138 if state != 0:
139 entry.rulelines.append(RuleLine(line[1], False))
140 state = 2
141 elif line[0] == "allow":
142 if state != 0:
143 entry.rulelines.append(RuleLine(line[1], True))
144 state = 2
145 elif line[0] == "crawl-delay":
146 if state != 0:
147 # before trying to convert to int we need to make
148 # sure that robots.txt has valid syntax otherwise
149 # it will crash
150 if line[1].strip().isdigit():
151 entry.delay = int(line[1])
152 state = 2
153 elif line[0] == "request-rate":
154 if state != 0:
155 numbers = line[1].split('/')
156 # check if all values are sane
157 if (len(numbers) == 2 and numbers[0].strip().isdigit()
158 and numbers[1].strip().isdigit()):
159 entry.req_rate = RequestRate(int(numbers[0]), int(numbers[1]))
160 state = 2
161 elif line[0] == "sitemap":
162 # According to http://www.sitemaps.org/protocol.html
163 # "This directive is independent of the user-agent line,
164 # so it doesn't matter where you place it in your file."
165 # Therefore we do not change the state of the parser.
166 self.sitemaps.append(line[1])
167 if state == 2:
168 self._add_entry(entry)
169
170 def can_fetch(self, useragent, url):
171 """using the parsed robots.txt decide if useragent can fetch url"""
172 if self.disallow_all:
173 return False
174 if self.allow_all:
175 return True
176 # Until the robots.txt file has been read or found not
177 # to exist, we must assume that no url is allowable.
178 # This prevents false positives when a user erroneously
179 # calls can_fetch() before calling read().
180 if not self.last_checked:
181 return False
182 # search for given user agent matches
183 # the first match counts
184 parsed_url = urllib.parse.urlsplit(url)
185 url = urllib.parse.urlunsplit(('', '', *parsed_url[2:]))
186 url = normalize_path(url)
187 if not url:
188 url = "/"
189 for entry in self.entries:
190 if entry.applies_to(useragent):
191 return entry.allowance(url)
192 # try the default entry last
193 if self.default_entry:
194 return self.default_entry.allowance(url)
195 # agent not found ==> access granted
196 return True
197
198 def crawl_delay(self, useragent):
199 if not self.mtime():
200 return None
201 for entry in self.entries:
202 if entry.applies_to(useragent):
203 return entry.delay
204 if self.default_entry:
205 return self.default_entry.delay
206 return None
207
208 def request_rate(self, useragent):
209 if not self.mtime():
210 return None
211 for entry in self.entries:
212 if entry.applies_to(useragent):
213 return entry.req_rate
214 if self.default_entry:
215 return self.default_entry.req_rate
216 return None
217
218 def site_maps(self):
219 if not self.sitemaps:
220 return None
221 return self.sitemaps
222
223 def __str__(self):
224 entries = self.entries
225 if self.default_entry is not None:
226 entries = entries + [self.default_entry]
227 return '\n\n'.join(map(str, entries))
228
229 class RuleLine:
230 """A rule line is a single "Allow:" (allowance==True) or "Disallow:"
231 (allowance==False) followed by a path."""
232 def __init__(self, path, allowance):
233 if path == '' and not allowance:
234 # an empty value means allow all
235 allowance = True
236 self.path = normalize_path(path)
237 self.allowance = allowance
238
239 def applies_to(self, filename):
240 return self.path == "*" or filename.startswith(self.path)
241
242 def __str__(self):
243 return ("Allow" if self.allowance else "Disallow") + ": " + self.path
244
245
246 class Entry:
247 """An entry has one or more user-agents and zero or more rulelines"""
248 def __init__(self):
249 self.useragents = []
250 self.rulelines = []
251 self.delay = None
252 self.req_rate = None
253
254 def __str__(self):
255 ret = []
256 for agent in self.useragents:
257 ret.append(f"User-agent: {agent}")
258 if self.delay is not None:
259 ret.append(f"Crawl-delay: {self.delay}")
260 if self.req_rate is not None:
261 rate = self.req_rate
262 ret.append(f"Request-rate: {rate.requests}/{rate.seconds}")
263 ret.extend(map(str, self.rulelines))
264 return '\n'.join(ret)
265
266 def applies_to(self, useragent):
267 """check if this entry applies to the specified agent"""
268 # split the name token and make it lower case
269 useragent = useragent.split("/")[0].lower()
270 for agent in self.useragents:
271 if agent == '*':
272 # we have the catch-all agent
273 return True
274 agent = agent.lower()
275 if agent in useragent:
276 return True
277 return False
278
279 def allowance(self, filename):
280 """Preconditions:
281 - our agent applies to this entry
282 - filename is URL encoded"""
283 for line in self.rulelines:
284 if line.applies_to(filename):
285 return line.allowance
286 return True