""" robotparser.pyCopyright (C) 2000 Bastian KleineidamYou can choose between two licenses when using this package:1) GNU GPLv22) PSF license for Python 2.2The robots.txt Exclusion Protocol is implemented as specified inhttp://www.robotstxt.org/norobots-rfc.txt"""import collectionsimport urllib.parseimport urllib.request__all__ = ["RobotFileParser"]RequestRate = collections.namedtuple("RequestRate", "requests seconds")class RobotFileParser:""" This class provides a set of methods to read, parse and answerquestions about a single robots.txt file."""def __init__(self, url=''):self.entries = []self.default_entry = Noneself.disallow_all = Falseself.allow_all = Falseself.set_url(url)self.last_checked = 0def mtime(self):"""Returns the time the robots.txt file was last fetched.This is useful for long-running web spiders that need tocheck for new robots.txt files periodically."""return self.last_checkeddef modified(self):"""Sets the time the robots.txt file was last fetched to thecurrent time."""import timeself.last_checked = time.time()def set_url(self, url):"""Sets the URL referring to a robots.txt file."""self.url = urlself.host, self.path = urllib.parse.urlparse(url)[1:3]def read(self):"""Reads the robots.txt URL and feeds it to the parser."""try:f = urllib.request.urlopen(self.url)except urllib.error.HTTPError as err:if err.code in (401, 403):self.disallow_all = Trueelif err.code >= 400 and err.code < 500:self.allow_all = Trueelse:raw = f.read()self.parse(raw.decode("utf-8").splitlines())def _add_entry(self, entry):if "*" in entry.useragents:# the default entry is considered lastif self.default_entry is None:# the first default entry winsself.default_entry = entryelse:self.entries.append(entry)def parse(self, lines):"""Parse the input lines from a robots.txt file.We allow that a user-agent: line is not preceded byone or more blank lines."""# states:# 0: start state# 1: saw user-agent line# 2: saw an allow or disallow linestate = 0entry = Entry()self.modified()for line in lines:if not line:if state == 1:entry = Entry()state = 0elif state == 2:self._add_entry(entry)entry = Entry()state = 0# remove optional comment and strip linei = line.find('#')if i >= 0:line = line[:i]line = line.strip()if not line:continueline = line.split(':', 1)if len(line) == 2:line[0] = line[0].strip().lower()line[1] = urllib.parse.unquote(line[1].strip())if line[0] == "user-agent":if state == 2:self._add_entry(entry)entry = Entry()entry.useragents.append(line[1])state = 1elif line[0] == "disallow":if state != 0:entry.rulelines.append(RuleLine(line[1], False))state = 2elif line[0] == "allow":if state != 0:entry.rulelines.append(RuleLine(line[1], True))state = 2elif line[0] == "crawl-delay":if state != 0:# before trying to convert to int we need to make# sure that robots.txt has valid syntax otherwise# it will crashif line[1].strip().isdigit():entry.delay = int(line[1])state = 2elif line[0] == "request-rate":if state != 0:numbers = line[1].split('/')# check if all values are saneif (len(numbers) == 2 and numbers[0].strip().isdigit()and numbers[1].strip().isdigit()):entry.req_rate = RequestRate(int(numbers[0]), int(numbers[1]))state = 2if state == 2:self._add_entry(entry)def can_fetch(self, useragent, url):"""using the parsed robots.txt decide if useragent can fetch url"""if self.disallow_all:return Falseif self.allow_all:return True# 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:return False# search for given user agent matches# the first match countsparsed_url = urllib.parse.urlparse(urllib.parse.unquote(url))url = urllib.parse.urlunparse(('','',parsed_url.path,parsed_url.params,parsed_url.query, parsed_url.fragment))url = urllib.parse.quote(url)if not url:url = "/"for entry in self.entries:if entry.applies_to(useragent):return entry.allowance(url)# try the default entry lastif self.default_entry:return self.default_entry.allowance(url)# agent not found ==> access grantedreturn Truedef crawl_delay(self, useragent):if not self.mtime():return Nonefor entry in self.entries:if entry.applies_to(useragent):return entry.delayif self.default_entry:return self.default_entry.delayreturn Nonedef request_rate(self, useragent):if not self.mtime():return Nonefor entry in self.entries:if entry.applies_to(useragent):return entry.req_rateif self.default_entry:return self.default_entry.req_ratereturn Nonedef __str__(self):entries = self.entriesif self.default_entry is not None:entries = entries + [self.default_entry]return '\n'.join(map(str, entries)) + '\n'class RuleLine:"""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 allallowance = Truepath = urllib.parse.urlunparse(urllib.parse.urlparse(path))self.path = urllib.parse.quote(path)self.allowance = allowancedef applies_to(self, filename):return self.path == "*" or filename.startswith(self.path)def __str__(self):return ("Allow" if self.allowance else "Disallow") + ": " + self.pathclass Entry:"""An entry has one or more user-agents and zero or more rulelines"""def __init__(self):self.useragents = []self.rulelines = []self.delay = Noneself.req_rate = Nonedef __str__(self):ret = []for agent in self.useragents:ret.append(f"User-agent: {agent}")if self.delay is not None:ret.append(f"Crawl-delay: {self.delay}")if self.req_rate is not None:rate = self.req_rateret.append(f"Request-rate: {rate.requests}/{rate.seconds}")ret.extend(map(str, self.rulelines))ret.append('') # for compatibilityreturn '\n'.join(ret)def applies_to(self, useragent):"""check if this entry applies to the specified agent"""# split the name token and make it lower caseuseragent = useragent.split("/")[0].lower()for agent in self.useragents:if agent == '*':# we have the catch-all agentreturn Trueagent = agent.lower()if agent in useragent:return Truereturn Falsedef allowance(self, filename):"""Preconditions:- our agent applies to this entry- filename is URL decoded"""for line in self.rulelines:if line.applies_to(filename):return line.allowancereturn True
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。