Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Use urlparse_cached() on request and responses

Paul Tremberth3af88a2877f9
diff --git a/scrapy/spidermiddlewares/referer.py b/scrapy/spidermiddlewares/referer.py
index 1895aa95d..cbbcd3e97 100644
--- a/scrapy/spidermiddlewares/referer.py
+++ b/scrapy/spidermiddlewares/referer.py
@@ -2,11 +2,12 @@
RefererMiddleware: populates Request referer field, based on the Response which
originated it.
"""
-from six.moves.urllib.parse import urlsplit, urlunsplit
+from six.moves.urllib.parse import urlparse, urlunparse, ParseResult
from scrapy.http import Request
from scrapy.exceptions import NotConfigured
from scrapy.utils.python import to_native_str
+from scrapy.utils.httpobj import urlparse_cached
LOCAL_SCHEMES = ('about', 'blob', 'data', 'filesystem',)
@@ -27,6 +28,46 @@ class ReferrerPolicy(object):
def referrer(self, response, request):
raise NotImplementedError()
+ def strip_url_parsed(self, req_or_resp, origin_only=False):
+ """
+ https://www.w3.org/TR/referrer-policy/#strip-url
+
+ If url is null, return no referrer.
+ If url's scheme is a local scheme, then return no referrer.
+ Set url's username to the empty string.
+ Set url's password to null.
+ Set url's fragment to null.
+ If the origin-only flag is true, then:
+ Set url's path to null.
+ Set url's query to null.
+ Return url.
+ """
+ if req_or_resp.url is None or not req_or_resp.url:
+ return None
+ parsed = urlparse_cached(req_or_resp)
+
+ if parsed.scheme in self.NOREFERRER_SCHEMES:
+ return None
+
+ netloc = parsed.netloc
+ # strip username and password if present
+ if parsed.username or parsed.password:
+ netloc = netloc.replace('{p.username}:{p.password}@'.format(p=parsed), '')
+
+ # strip standard protocol numbers
+ # Note: strictly speaking, standard port numbers should only be
+ # stripped when comparing origins
+ if parsed.port:
+ if (parsed.scheme, parsed.port) in (('http', 80), ('https', 443)):
+ netloc = netloc.replace(':{p.port}'.format(p=parsed), '')
+
+ return ParseResult(parsed.scheme,
+ netloc,
+ '/' if origin_only else parsed.path,
+ '' if origin_only else parsed.params,
+ '' if origin_only else parsed.query,
+ '')
+
def strip_url(self, url, origin_only=False):
"""
https://www.w3.org/TR/referrer-policy/#strip-url
@@ -43,7 +84,7 @@ class ReferrerPolicy(object):
"""
if url is None or not url:
return None
- parsed = urlsplit(url, allow_fragments=True)
+ parsed = urlparse(url, allow_fragments=True)
if parsed.scheme in self.NOREFERRER_SCHEMES:
return None
@@ -60,16 +101,21 @@ class ReferrerPolicy(object):
if (parsed.scheme, parsed.port) in (('http', 80), ('https', 443)):
netloc = netloc.replace(':{p.port}'.format(p=parsed), '')
- return urlunsplit((
+ return urlunparse((
parsed.scheme,
netloc,
'/' if origin_only else parsed.path,
+ '' if origin_only else parsed.params,
'' if origin_only else parsed.query,
''))
def origin(self, url):
return self.strip_url(url, origin_only=True)
+ def origin_parsed(self, req_or_resp):
+ """Return (scheme, host, path) tuple for a request or response URL."""
+ return tuple(self.strip_url_parsed(req_or_resp, origin_only=True)[:3])
+
class NoReferrerPolicy(ReferrerPolicy):
"""
@@ -103,20 +149,17 @@ class NoReferrerWhenDowngradePolicy(ReferrerPolicy):
name = POLICY_NO_REFERRER_WHEN_DOWNGRADE
def referrer(self, response, request):
- target_url = request.url
-
- referrer_source = response.url
- referrer_url = self.strip_url(referrer_source)
-
# https://www.w3.org/TR/referrer-policy/#determine-requests-referrer:
#
# If environment is TLS-protected
# and the origin of request's current URL is not an a priori authenticated URL,
# then return no referrer.
- if urlsplit(referrer_source).scheme in ('https', 'ftps') and \
- urlsplit(target_url).scheme in ('http',):
+ if urlparse_cached(response).scheme in ('https', 'ftps') and \
+ urlparse_cached(request).scheme in ('http',):
return None
- return referrer_url
+ stripped = self.strip_url_parsed(response)
+ if stripped is not None:
+ return urlunparse(stripped)
class SameOriginPolicy(ReferrerPolicy):
@@ -132,12 +175,10 @@ class SameOriginPolicy(ReferrerPolicy):
name = POLICY_SAME_ORIGIN
def referrer(self, response, request):
- target_url = request.url
- referrer_source = response.url
- if self.origin(referrer_source) == self.origin(target_url):
- return self.strip_url(referrer_source)
- else:
- return None
+ if self.origin_parsed(response) == self.origin_parsed(request):
+ stripped = self.strip_url_parsed(response)
+ if stripped is not None:
+ return urlunparse(stripped)
class OriginPolicy(ReferrerPolicy):