Skip to content

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

Cache URL parses per URL and parse fewer URLs per request (#8247)

Adrian229c1b8c9052
diff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.py
index e105ed908..81506f4aa 100644
--- a/scrapy/core/downloader/handlers/http11.py
+++ b/scrapy/core/downloader/handlers/http11.py
@@ -10,7 +10,7 @@ from functools import partial
from io import BytesIO
from time import monotonic
from typing import TYPE_CHECKING, Any, NotRequired, TypedDict, TypeVar, cast
-from urllib.parse import urldefrag, urlparse
+from urllib.parse import urldefrag
from twisted.internet import ssl
from twisted.internet.defer import Deferred, succeed
@@ -472,7 +472,7 @@ class _ScrapyAgent:
proxy = request.meta.get("proxy")
if proxy:
proxy = _add_http_if_no_scheme(proxy)
- proxy_parsed = urlparse(proxy)
+ proxy_parsed = urlparse_cached(proxy)
proxy_host = proxy_parsed.hostname
proxy_port = proxy_parsed.port
if not proxy_port:
diff --git a/scrapy/downloadermiddlewares/httpauth.py b/scrapy/downloadermiddlewares/httpauth.py
index b3c769c6a..106d96402 100644
--- a/scrapy/downloadermiddlewares/httpauth.py
+++ b/scrapy/downloadermiddlewares/httpauth.py
@@ -74,12 +74,12 @@ class HttpAuthMiddleware:
pwd = request.meta.get("http_pass", "")
if usr or pwd:
domain = request.meta.get("http_auth_domain")
- if not domain or url_is_from_any_domain(request.url, [domain]):
+ if not domain or url_is_from_any_domain(request, [domain]):
request.headers[b"Authorization"] = basic_auth_header(usr, pwd)
return None
# Middleware-level auth
if self._auth and (
- not self._domain or url_is_from_any_domain(request.url, [self._domain])
+ not self._domain or url_is_from_any_domain(request, [self._domain])
):
request.headers[b"Authorization"] = self._auth
return None
diff --git a/scrapy/linkextractors/lxmlhtml.py b/scrapy/linkextractors/lxmlhtml.py
index 6089f1cd0..beae807e4 100644
--- a/scrapy/linkextractors/lxmlhtml.py
+++ b/scrapy/linkextractors/lxmlhtml.py
@@ -10,7 +10,7 @@ import re
from collections.abc import Callable, Iterable
from functools import partial
from typing import TYPE_CHECKING, Any, TypeAlias, cast
-from urllib.parse import urljoin, urlparse
+from urllib.parse import urljoin
from lxml import etree
from parsel.csstranslator import HTMLTranslator
@@ -19,10 +19,11 @@ from w3lib.url import canonicalize_url, safe_url_string
from scrapy.link import Link
from scrapy.linkextractors import IGNORED_EXTENSIONS, SUPPORTED_SCHEMES, _matches
+from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.misc import arg_to_iter, rel_has_nofollow
from scrapy.utils.python import unique as unique_list
from scrapy.utils.response import get_base_url
-from scrapy.utils.url import url_has_any_extension, url_is_from_any_domain
+from scrapy.utils.url import url_is_from_any_domain
if TYPE_CHECKING:
from lxml.html import HtmlElement
@@ -57,6 +58,18 @@ def _canonicalize_link_url(link: Link) -> str:
return canonicalize_url(link.url, keep_fragments=True)
+def _has_extension(path: str, extensions: set[str]) -> bool:
+ """Return whether *path* ends with any of *extensions*, which all start
+ with a dot and are lowercase, ignoring case.
+ """
+ dot = path.rfind(".")
+ while dot != -1:
+ if path[dot:].lower() in extensions:
+ return True
+ dot = path.rfind(".", 0, dot)
+ return False
+
+
def _name_matches(allowed: set[str], denied: set[str], name: str) -> bool:
"""Return whether a tag or attribute *name* should be considered.
@@ -371,7 +384,7 @@ class LxmlLinkExtractor:
]
def _link_allowed(self, link: Link) -> bool:
- parsed_url = urlparse(link.url)
+ parsed_url = urlparse_cached(link.url)
if self.schemes and parsed_url.scheme not in self.schemes:
return False
if self.allow_res and not _matches(link.url, self.allow_res):
@@ -384,8 +397,8 @@ class LxmlLinkExtractor:
return False
if self.deny_domains and url_is_from_any_domain(parsed_url, self.deny_domains):
return False
- if self.deny_extensions and url_has_any_extension(
- parsed_url, self.deny_extensions
+ if self.deny_extensions and _has_extension(
+ parsed_url.path, self.deny_extensions
):
return False
return not self.restrict_text or _matches(link.text, self.restrict_text)
diff --git a/scrapy/spidermiddlewares/referer.py b/scrapy/spidermiddlewares/referer.py
index 399b221d0..891de5bfe 100644
--- a/scrapy/spidermiddlewares/referer.py
+++ b/scrapy/spidermiddlewares/referer.py
@@ -7,13 +7,14 @@ from __future__ import annotations
import warnings
from abc import ABC, abstractmethod
+from functools import lru_cache
from typing import TYPE_CHECKING, Self, TypedDict, Unpack, cast
-from urllib.parse import urlparse
from warnings import warn
from scrapy.exceptions import NotConfigured, ScrapyDeprecationWarning
from scrapy.http import Request, Response
from scrapy.spidermiddlewares.base import BaseSpiderMiddleware
+from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.misc import load_object
from scrapy.utils.python import _looks_like_import_path, to_unicode
from scrapy.utils.url import strip_url
@@ -26,6 +27,13 @@ if TYPE_CHECKING:
resp_or_url: Response | str
+# Every request that a response yields gets its referrer from the URL of that
+# response.
+@lru_cache
+def _strip_url(url: str, origin_only: bool) -> str:
+ return strip_url(url, origin_only=origin_only)
+
+
LOCAL_SCHEMES: tuple[str, ...] = (
"about",
"blob",
@@ -55,12 +63,12 @@ class ReferrerPolicy(ABC):
raise NotImplementedError
def stripped_referrer(self, url: str) -> str | None:
- if urlparse(url).scheme not in self.NOREFERRER_SCHEMES:
+ if urlparse_cached(url).scheme not in self.NOREFERRER_SCHEMES:
return self.strip_url(url)
return None
def origin_referrer(self, url: str) -> str | None:
- if urlparse(url).scheme not in self.NOREFERRER_SCHEMES:
+ if urlparse_cached(url).scheme not in self.NOREFERRER_SCHEMES:
return self.origin(url)
return None
@@ -80,13 +88,7 @@ class ReferrerPolicy(ABC):
"""
if not url:
return None
- return strip_url(
- url,
- strip_credentials=True,
- strip_fragment=True,
- strip_default_port=True,
- origin_only=origin_only,
- )
+ return _strip_url(url, origin_only)
def origin(self, url: str) -> str | None:
"""Return serialized origin (scheme, host, port) for a request or response URL."""
@@ -94,13 +96,13 @@ class ReferrerPolicy(ABC):
def potentially_trustworthy(self, url: str) -> bool:
# Note: this does not follow https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy
- parsed_url = urlparse(url)
+ parsed_url = urlparse_cached(url)
if parsed_url.scheme == "data":
return False
return self.tls_protected(url)
def tls_protected(self, url: str) -> bool:
- return urlparse(url).scheme in {"https", "ftps"}
+ return urlparse_cached(url).scheme in {"https", "ftps"}
class NoReferrerPolicy(ReferrerPolicy):
diff --git a/scrapy/spiders/__init__.py b/scrapy/spiders/__init__.py
index 6a098c6e5..91426dbe9 100644
--- a/scrapy/spiders/__init__.py
+++ b/scrapy/spiders/__init__.py
@@ -166,7 +166,7 @@ class Spider(object_ref):
@classmethod
def handles_request(cls, request: Request) -> bool:
- return url_is_from_spider(request.url, cls)
+ return url_is_from_spider(request, cls)
@staticmethod
def close(spider: Spider, reason: str) -> Deferred[None] | None:
diff --git a/scrapy/utils/httpobj.py b/scrapy/utils/httpobj.py
index 5965e1f21..4a702a7de 100644
--- a/scrapy/utils/httpobj.py
+++ b/scrapy/utils/httpobj.py
@@ -2,30 +2,65 @@
from __future__ import annotations
+from collections import OrderedDict
from typing import TYPE_CHECKING
from urllib.parse import ParseResult, urlparse
-from weakref import WeakKeyDictionary
+from weakref import WeakKeyDictionary, WeakValueDictionary
if TYPE_CHECKING:
from scrapy.http import Request, Response
-_urlparse_cache: WeakKeyDictionary[Request | Response, ParseResult] = (
- WeakKeyDictionary()
-)
+class _Entry:
+ __slots__ = ("__weakref__", "result")
+ def __init__(self, result: ParseResult):
+ self.result = result
-def urlparse_cached(request_or_response: Request | Response) -> ParseResult:
- """Return the result of parsing the URL of *request_or_response*, a
- :class:`~scrapy.Request` or :class:`~scrapy.http.Response` object, with
- :func:`urllib.parse.urlparse`.
- The result is cached, using a :class:`weakref.WeakKeyDictionary` keyed on
- *request_or_response*, so that the URL of a given object is parsed only
- once. Prefer this function over calling :func:`urllib.parse.urlparse` on
- ``request_or_response.url`` directly when the same URL may be parsed more
- than once.
+# Requests and responses hold the entry of their URL, which is dropped once
+# none of them does. Results for URL strings that no request or response holds
+# are kept in _string_results, for the most recently parsed ones.
+_entries_by_url: WeakValueDictionary[str, _Entry] = WeakValueDictionary()
+_entries_by_object: WeakKeyDictionary[Request | Response, _Entry] = WeakKeyDictionary()
+_string_results: OrderedDict[str, ParseResult] = OrderedDict()
+# URL strings are often parsed shortly before a request is built from them,
+# e.g. link URLs, so their results must outlive a whole page worth of them.
+_MAX_STRING_RESULTS = 1024
+
+
+def urlparse_cached(request_or_response: Request | Response | str) -> ParseResult:
+ """Return the result of parsing *request_or_response*, a
+ :class:`~scrapy.Request` or :class:`~scrapy.http.Response` object or a
+ URL, with :func:`urllib.parse.urlparse`.
+
+ .. versionchanged:: VERSION
+ *request_or_response* can be a URL.
+
+ The result is cached and shared by everything with the same URL: for as
+ long as a request or response with that URL exists, or else for a limited
+ number of recently parsed URLs. So pass a request or response rather than
+ its URL whenever you can, and prefer this function over
+ :func:`urllib.parse.urlparse` when the same URL may be parsed more than
+ once.
"""
- if request_or_response not in _urlparse_cache:
- _urlparse_cache[request_or_response] = urlparse(request_or_response.url)
- return _urlparse_cache[request_or_response]
+ if isinstance(request_or_response, str):
+ url = request_or_response
+ result = _string_results.get(url)
+ if result is None:
+ entry = _entries_by_url.get(url)
+ if entry is not None:
+ return entry.result
+ result = _string_results[url] = urlparse(url)
+ if len(_string_results) > _MAX_STRING_RESULTS:
+ _string_results.popitem(last=False)
+ return result
+ entry = _entries_by_object.get(request_or_response)
+ if entry is None:
+ url = request_or_response.url
+ entry = _entries_by_url.get(url)
+ if entry is None:
+ result = _string_results.pop(url, None) or urlparse(url)
+ entry = _entries_by_url[url] = _Entry(result)
+ _entries_by_object[request_or_response] = entry
+ return entry.result
diff --git a/scrapy/utils/url.py b/scrapy/utils/url.py
index de2e38728..d5e2d700f 100644
--- a/scrapy/utils/url.py
+++ b/scrapy/utils/url.py
@@ -8,24 +8,34 @@ from __future__ import annotations
import re
import warnings
from typing import TYPE_CHECKING, TypeAlias
-from urllib.parse import ParseResult, urlparse, urlunparse
+from urllib.parse import ParseResult, urlunparse
import w3lib.url
from w3lib.url import any_to_uri, parse_url
from scrapy.exceptions import ScrapyDeprecationWarning
+from scrapy.utils.httpobj import urlparse_cached
if TYPE_CHECKING:
from collections.abc import Iterable
from scrapy import Spider
+ from scrapy.http import Request, Response
UrlT: TypeAlias = str | bytes | ParseResult
-def url_is_from_any_domain(url: UrlT, domains: Iterable[str]) -> bool:
+def _parse_url(url: UrlT | Request | Response) -> ParseResult:
+ if isinstance(url, (bytes, ParseResult)):
+ return parse_url(url)
+ return urlparse_cached(url)
+
+
+def url_is_from_any_domain(
+ url: UrlT | Request | Response, domains: Iterable[str]
+) -> bool:
"""Return True if the url belongs to any of the given domains"""
- host = parse_url(url).netloc.lower()
+ host = _parse_url(url).netloc.lower()
if not host:
return False
return any((host == d) or (host.endswith(f".{d}")) for d in map(str.lower, domains))
@@ -49,20 +59,22 @@ def _spider_domains(spider: type[Spider]) -> Iterable[str]:
yield from allowed_domains
-def url_is_from_spider(url: UrlT, spider: type[Spider]) -> bool:
+def url_is_from_spider(url: UrlT | Request | Response, spider: type[Spider]) -> bool:
"""Return True if the url belongs to the given spider"""
return url_is_from_any_domain(url, _spider_domains(spider))
-def url_has_any_extension(url: UrlT, extensions: Iterable[str]) -> bool:
+def url_has_any_extension(
+ url: UrlT | Request | Response, extensions: Iterable[str]
+) -> bool:
"""Return True if the url ends with one of the extensions provided"""
- lowercase_path = parse_url(url).path.lower()
+ lowercase_path = _parse_url(url).path.lower()
return any(lowercase_path.endswith(ext) for ext in extensions)
def _add_http_if_no_scheme(url: str) -> str:
if not re.match(r"^\w+://", url, flags=re.IGNORECASE):
- scheme = "http:" if urlparse(url).netloc else "http://"
+ scheme = "http:" if urlparse_cached(url).netloc else "http://"
url = scheme + url
return url
@@ -146,7 +158,7 @@ def strip_url(
- ``strip_fragment`` drops any #fragment component
"""
- parsed_url = urlparse(url)
+ parsed_url = urlparse_cached(url)
netloc = parsed_url.netloc
if (strip_credentials or origin_only) and (
parsed_url.username or parsed_url.password
diff --git a/tests/test_linkextractors.py b/tests/test_linkextractors.py
index d200c585c..e440b6775 100644
--- a/tests/test_linkextractors.py
+++ b/tests/test_linkextractors.py
@@ -4,6 +4,7 @@ import pickle
import re
from typing import Any
+import pytest
from w3lib.url import canonicalize_url
from scrapy.http import HtmlResponse, TextResponse, XmlResponse
@@ -348,6 +349,22 @@ class TestLxmlLinkExtractor:
Link(url="http://example.org/photo.jpg"),
]
+ @pytest.mark.parametrize(
+ ("path", "denied"),
+ [
+ ("/file.tar.gz", True),
+ ("/FILE.TAR.GZ", True),
+ ("/file.gz", False),
+ ("/file.tar.gz/page", False),
+ ("/file", False),
+ ],
+ )
+ def test_ignored_multi_part_extension(self, path: str, denied: bool) -> None:
+ html = f'<a href="{path}">x</a>'.encode()
+ response = HtmlResponse("http://example.org/", body=html)
+ lx = LxmlLinkExtractor(deny_extensions=["tar.gz"])
+ assert (not lx.extract_links(response)) is denied
+
def test_process_value(self):
"""Test restrict_xpaths with encodings"""
html = b"""
diff --git a/tests/test_utils_httpobj.py b/tests/test_utils_httpobj.py
index 610c463ec..eb9852784 100644
--- a/tests/test_utils_httpobj.py
+++ b/tests/test_utils_httpobj.py
@@ -1,12 +1,17 @@
from __future__ import annotations
+from collections import OrderedDict
from urllib.parse import urlparse
-from scrapy.http import Request
+import pytest
+
+from scrapy.http import Request, Response
+from scrapy.utils import httpobj
from scrapy.utils.httpobj import urlparse_cached
+from scrapy.utils.python import garbage_collect
-def test_urlparse_cached():
+def test_urlparse_cached() -> None:
url = "http://www.example.com/index.html"
request1 = Request(url)
request2 = Request(url)
@@ -15,8 +20,50 @@ def test_urlparse_cached():
req2 = urlparse_cached(request2)
urlp = urlparse(url)
- assert req1a == req2
assert req1a == urlp
assert req1a is req1b
- assert req1a is not req2
- assert req1b is not req2
+ assert req1a is req2
+ assert urlparse_cached(url) is req1a
+
+
+def test_urlparse_cached_shared_by_url() -> None:
+ url = "http://www.example.com/shared"
+ parsed = urlparse_cached(url)
+ request = Request(url)
+ assert urlparse_cached(request) is parsed
+ assert urlparse_cached(Response(url, request=request)) is parsed
+
+
[email protected]("url_first", [True, False], ids=["url-first", "url-last"])
+ "holders",
+ [["request"], ["response"], ["request", "response"]],
+ ids=["request", "response", "both"],
+)
+def test_urlparse_cached_lifetime(url_first: bool, holders: list[str]) -> None:
+ url = f"http://www.example.com/{'-'.join(holders)}/{url_first}"
+ if url_first:
+ parsed = urlparse_cached(url)
+ objects: list[Request | Response] = [
+ Request(url) if holder == "request" else Response(url) for holder in holders
+ ]
+ if not url_first:
+ parsed = urlparse_cached(objects[0])
+ assert all(urlparse_cached(obj) is parsed for obj in objects)
+ assert urlparse_cached(url) is parsed
+ while objects:
+ assert urlparse_cached(Request(url)) is parsed
+ objects.pop(0)
+ garbage_collect()
+ assert urlparse_cached(Request(url)) is not parsed
+
+
+def test_urlparse_cached_string_eviction(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(httpobj, "_string_results", OrderedDict())
+ monkeypatch.setattr(httpobj, "_MAX_STRING_RESULTS", 2)
+ url = "http://www.example.com/evicted"
+ parsed = urlparse_cached(url)
+ assert urlparse_cached(url) is parsed
+ urlparse_cached("http://www.example.com/evicted/1")
+ urlparse_cached("http://www.example.com/evicted/2")
+ assert urlparse_cached(url) is not parsed
diff --git a/tests/test_utils_url.py b/tests/test_utils_url.py
index 830d691e2..81b333dc2 100644
--- a/tests/test_utils_url.py
+++ b/tests/test_utils_url.py
@@ -1,9 +1,13 @@
from __future__ import annotations
+from typing import Any
+from urllib.parse import urlparse
+
import pytest
import w3lib.url
from scrapy.exceptions import ScrapyDeprecationWarning
+from scrapy.http import Request, Response
from scrapy.linkextractors import IGNORED_EXTENSIONS
from scrapy.spiders import Spider
from scrapy.utils.url import (
@@ -43,6 +47,22 @@ def test_url_is_from_any_domain():
assert not url_is_from_any_domain(url + ".testdomain.com", ["testdomain.com"])
+ "url",
+ [
+ "https://www.example.com/page",
+ b"https://www.example.com/page",
+ urlparse("https://www.example.com/page"),
+ Request("https://www.example.com/page"),
+ Response("https://www.example.com/page"),
+ ],
+ ids=["str", "bytes", "ParseResult", "Request", "Response"],
+)
+def test_url_is_from_any_domain_input_types(url: Any) -> None:
+ assert url_is_from_any_domain(url, ["example.com"])
+ assert not url_is_from_any_domain(url, ["example.org"])
+
+
def test_url_is_from_spider():
class MySpider(Spider):
name = "example.com"