Skip to content

Commit 6f9e3f5

Browse files
committed
Addressing RobotFileParser review comments.
1 parent 1959b02 commit 6f9e3f5

4 files changed

Lines changed: 33 additions & 59 deletions

File tree

Doc/library/urllib.robotparser.rst

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,21 @@ website that published the :file:`robots.txt` file. For more details on the
2121
structure of :file:`robots.txt` files, see :rfc:`9309`.
2222

2323

24-
.. class:: RobotFileParser(url_or_request='')
24+
.. class:: RobotFileParser(url='')
2525

2626
This class provides methods to read, parse and answer questions about the
27-
:file:`robots.txt` file at *url* or a :class:`urllib.request.Request` object
28-
with additional user-agent headers populated.
27+
:file:`robots.txt` file at *url* or a :class:`urllib.request.Request` object.
2928

29+
.. versionchanged:: 3.16
30+
*url* parameter can be a :class:`urllib.request.Request` object.
3031

31-
.. method:: set_url(url_or_request)
32+
.. method:: set_url(url)
3233

3334
Sets the URL referring to a :file:`robots.txt` file or a
34-
:class:`urllib.request.Request` object with additional user-agent headers
35-
populated.
35+
:class:`urllib.request.Request` object.
36+
37+
.. versionchanged:: 3.16
38+
*url* parameter can be a :class:`urllib.request.Request` object.
3639

3740
.. method:: read()
3841

@@ -114,9 +117,9 @@ object with additional user-agent headers populated::
114117
>>> import urllib.robotparser
115118
>>> import urllib.request
116119
>>> rp = urllib.robotparser.RobotFileParser()
117-
>>> rp.set_url(urllib.request.Request("http://en.wikipedia.org/robots.txt", headers={"User-Agent": "IsraBot"}))
120+
>>> rp.set_url(urllib.request.Request("http://www.pythontest.net/robots.txt", headers={"User-Agent": "IsraBot"}))
118121
>>> rp.read()
119-
>>> rp.can_fetch("*", "https://en.wikipedia.org/")
122+
>>> rp.can_fetch("*", "http://www.pythontest.net/")
120123
True
121-
>>> rp.can_fetch("*", "https://en.wikipedia.org/trap/")
124+
>>> rp.can_fetch("*", "https://www.pythontest.net/no-robots-here/")
122125
False

Lib/test/test_robotparser.py

Lines changed: 12 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -773,51 +773,23 @@ def testServiceUnavailable(self):
773773
self.assertFalse(parser.can_fetch("*", url + '/path/file.html'))
774774

775775

776-
class UserAgentRobotHandler(BaseHTTPRequestHandler):
776+
class UserAgentSiteTestCase(BaseLocalNetworkTestCase, unittest.TestCase):
777777

778-
def do_GET(self):
779-
if self.headers.get('User-Agent').startswith('Python-urllib'):
780-
self.send_error(403, "Forbidden access")
781-
else:
782-
self.send_response(200)
783-
self.end_headers()
784-
self.wfile.write(b"User-agent: *\nDisallow:")
785-
786-
def log_message(self, format, *args):
787-
pass
788-
789-
790-
@unittest.skipUnless(
791-
support.has_socket_support,
792-
"Socket server requires working socket."
793-
)
794-
class UserAgentSiteTestCase(unittest.TestCase):
795-
796-
def setUp(self):
797-
# clear _opener global variable
798-
self.addCleanup(urllib.request.urlcleanup)
799-
800-
self.server = HTTPServer((socket_helper.HOST, 0), UserAgentRobotHandler)
801-
802-
self.t = threading.Thread(
803-
name='HTTPServer serving',
804-
target=self.server.serve_forever,
805-
# Short poll interval to make the test finish quickly.
806-
# Time between requests is short enough that we won't wake
807-
# up spuriously too many times.
808-
kwargs={'poll_interval':0.01})
809-
self.t.daemon = True # In case this function raises.
810-
self.t.start()
778+
class RobotHandler(BaseHTTPRequestHandler):
779+
def do_GET(self):
780+
if self.headers.get('User-Agent').startswith('Python-urllib'):
781+
self.send_error(403, "Forbidden access")
782+
else:
783+
self.send_response(200)
784+
self.end_headers()
785+
self.wfile.write(b"User-agent: *\nDisallow:")
811786

812-
def tearDown(self):
813-
self.server.shutdown()
814-
self.t.join()
815-
self.server.server_close()
787+
def log_message(self, format, *args):
788+
pass
816789

817-
@threading_helper.reap_threads
818790
def testUserAgentFilteringSite(self):
819791
addr = self.server.server_address
820-
url = 'http://' + socket_helper.HOST + ':' + str(addr[1])
792+
url = f'http://{socket_helper.HOST}:{addr[1]}'
821793
robots_url = url + "/robots.txt"
822794
file_url = url + "/document"
823795
parser = urllib.robotparser.RobotFileParser()

Lib/urllib/robotparser.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,14 @@ class RobotFileParser:
2727
2828
"""
2929

30-
def __init__(self, url_or_request=''):
30+
def __init__(self, url=''):
3131
self.entries = []
3232
self.groups = {}
3333
self.sitemaps = []
3434
self.default_entry = None
3535
self.disallow_all = False
3636
self.allow_all = False
37-
self.set_url(url_or_request)
37+
self.set_url(url)
3838
self.last_checked = 0
3939

4040
def mtime(self):
@@ -54,17 +54,16 @@ def modified(self):
5454
import time
5555
self.last_checked = time.time()
5656

57-
def set_url(self, url_or_request):
57+
def set_url(self, url):
5858
"""Sets the URL referring to a robots.txt file.
59-
url_or_request can be a string or a Request object.
59+
can be a string or a Request object.
6060
"""
61-
self.url = url_or_request
61+
self.url = url
6262

63-
if isinstance(url_or_request, urllib.request.Request):
64-
self.host = url_or_request.host
65-
self.path = url_or_request.selector
63+
if isinstance(url, urllib.request.Request):
64+
self.host, self.path = urllib.parse.urlsplit(url.full_url)[1:3]
6665
else:
67-
self.host, self.path = urllib.parse.urlparse(url_or_request)[1:3]
66+
self.host, self.path = urllib.parse.urlsplit(url)[1:3]
6867

6968
def read(self):
7069
"""Reads the robots.txt URL and feeds it to the parser."""
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
Let ``urllib.robotparser.RobotParser`` accept a ``urllib.request.Request`` object as well as a url string when setting a robots.txt url.
1+
Let ``urllib.robotparser.RobotFileParser`` accept a ``urllib.request.Request`` object as well as a url string when setting a robots.txt url.

0 commit comments

Comments
 (0)