Scrapy, a fast high-level web crawling & scraping framework for Python.
Link extractors and SitemapSpider follow file://, ftp:// and s3:// URLs from crawled content
Adrian Chaves2b30fee43563
diff --git a/docs/news.rst b/docs/news.rstindex 0a7d29e37..bca257324 100644--- a/docs/news.rst+++ b/docs/news.rst@@ -108,6 +108,26 @@ Security bug fixes.. _fwm7-29m4-rrj9: https://github.com/scrapy/scrapy/security/advisories/GHSA-fwm7-29m4-rrj9+- :class:`~scrapy.linkextractors.lxmlhtml.LxmlLinkExtractor` and+ :class:`~scrapy.spiders.SitemapSpider` now only follow ``http://`` and+ ``https://`` URLs by default, plus URLs that use the scheme of the response+ they come from.++ In previous Scrapy versions, link extractors also followed ``file://`` and+ ``ftp://`` URLs, and :class:`~scrapy.spiders.SitemapSpider` followed URLs+ of any scheme. A crawled website could use that to make Scrapy read local+ files, send the :setting:`FTP_USER` and :setting:`FTP_PASSWORD` credentials+ to an FTP server of its choosing, or send requests signed with the+ :setting:`AWS_ACCESS_KEY_ID` credentials to an S3 bucket of its choosing.+ See the `q7wc-mr9r-gcjh`_ security advisory for details.++ To follow URLs with other schemes, use the new ``schemes`` parameter of+ :class:`~scrapy.linkextractors.lxmlhtml.LxmlLinkExtractor` or the new+ :attr:`~scrapy.spiders.SitemapSpider.sitemap_schemes` attribute of+ :class:`~scrapy.spiders.SitemapSpider`.++ .. _q7wc-mr9r-gcjh: https://github.com/scrapy/scrapy/security/advisories/GHSA-q7wc-mr9r-gcjh+Modified requirements~~~~~~~~~~~~~~~~~~~~~@@ -358,14 +378,6 @@ Backward-incompatible changesentry.(:gh:`7820`, :gh:`8159`)-- :class:`~scrapy.linkextractors.lxmlhtml.LxmlLinkExtractor` now also- extracts links with the ``data`` and ``s3`` schemes by default, since- Scrapy can download them. Use its new ``schemes`` parameter, which- defaults to :data:`scrapy.linkextractors.SUPPORTED_SCHEMES`, to choose the- URL schemes of extracted links, e.g. ``schemes=["file", "ftp", "http",- "https"]`` to extract only the schemes that it extracted before.- (:gh:`4979`, :gh:`7994`)-- :class:`HttpCompressionMiddleware<scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware>`now raises :exc:`~scrapy.exceptions.DecompressionError` for a response body@@ -1131,6 +1143,12 @@ New features:mod:`hashlib` algorithm other than MD5.(:gh:`3306`, :gh:`7951`)+- :class:`~scrapy.linkextractors.lxmlhtml.LxmlLinkExtractor` has a new+ ``schemes`` parameter to choose the URL schemes of extracted links, and+ :data:`scrapy.linkextractors.SUPPORTED_SCHEMES` lists the URL schemes that+ Scrapy can download out of the box.+ (:gh:`4979`, :gh:`7994`)+- Added :meth:`SitemapSpider.sitemap_request()<scrapy.spiders.SitemapSpider.sitemap_request>`, which you can override tocustomize the requests that :class:`~scrapy.spiders.SitemapSpider` buildsdiff --git a/scrapy/linkextractors/__init__.py b/scrapy/linkextractors/__init__.pyindex cb4d22022..77e94ab2c 100644--- a/scrapy/linkextractors/__init__.py+++ b/scrapy/linkextractors/__init__.py@@ -126,9 +126,10 @@ SUPPORTED_SCHEMES = ["https","s3",]-"""URL schemes that Scrapy can download out of the box, and hence the default-value of the ``schemes`` parameter of :class:`LinkExtractor-<scrapy.linkextractors.lxmlhtml.LxmlLinkExtractor>`."""+"""URL schemes that Scrapy can download out of the box. Pass it as the+``schemes`` parameter of :class:`LinkExtractor+<scrapy.linkextractors.lxmlhtml.LxmlLinkExtractor>` to extract links that use+any of them."""def _matches(url: str, regexs: Iterable[Pattern[str]]) -> bool:diff --git a/scrapy/linkextractors/lxmlhtml.py b/scrapy/linkextractors/lxmlhtml.pyindex 3182b3f57..db28ff489 100644--- a/scrapy/linkextractors/lxmlhtml.py+++ b/scrapy/linkextractors/lxmlhtml.py@@ -18,7 +18,7 @@ from w3lib.html import strip_html5_whitespacefrom w3lib.url import canonicalize_url, safe_url_stringfrom scrapy.link import Link-from scrapy.linkextractors import IGNORED_EXTENSIONS, SUPPORTED_SCHEMES, _matches+from scrapy.linkextractors import IGNORED_EXTENSIONS, _matchesfrom scrapy.utils.httpobj import urlparse_cachedfrom scrapy.utils.misc import arg_to_iter, rel_has_nofollowfrom scrapy.utils.python import unique as unique_list@@ -215,9 +215,9 @@ class LxmlLinkExtractor::type deny_extensions: list:param schemes: a single value or list of strings containing the URL- schemes that extracted links may use. If not given, it will default to- :data:`scrapy.linkextractors.SUPPORTED_SCHEMES`. Use ``()`` to extract- links regardless of their scheme.+ schemes that extracted links may use. If not given, links may only use+ ``http``, ``https`` or the scheme of the response. Use ``()`` to+ extract links regardless of their scheme... versionadded:: 2.20.0:type schemes: str or list@@ -368,11 +368,11 @@ class LxmlLinkExtractor:if deny_extensions is None:deny_extensions = IGNORED_EXTENSIONS- if schemes is None:- schemes = SUPPORTED_SCHEMESself.canonicalize: bool = canonicalizeself.deny_extensions: set[str] = {"." + e for e in arg_to_iter(deny_extensions)}- self.schemes: set[str] = set(arg_to_iter(schemes))+ self.schemes: set[str] | None = (+ None if schemes is None else set(arg_to_iter(schemes))+ )self.restrict_text: list[re.Pattern[str]] = self._compile_regexes(restrict_text)@staticmethod@@ -382,9 +382,9 @@ class LxmlLinkExtractor:for x in arg_to_iter(value)]- def _link_allowed(self, link: Link) -> bool:+ def _link_allowed(self, link: Link, schemes: set[str]) -> bool:parsed_url = urlparse_cached(link.url)- if self.schemes and parsed_url.scheme not in self.schemes:+ if schemes and parsed_url.scheme not in schemes:return Falseif self.allow_res and not _matches(link.url, self.allow_res):return False@@ -416,8 +416,8 @@ class LxmlLinkExtractor:denied = (regex.search(url) for regex in self.deny_res) if self.deny_res else ()return any(allowed) and not any(denied)- def _process_links(self, links: list[Link]) -> list[Link]:- links = [x for x in links if self._link_allowed(x)]+ def _process_links(self, links: list[Link], schemes: set[str]) -> list[Link]:+ links = [x for x in links if self._link_allowed(x, schemes)]if self.canonicalize:for link in links:link.url = canonicalize_url(link.url)@@ -444,10 +444,15 @@ class LxmlLinkExtractor:]else:docs = [response.selector]+ schemes = (+ {"http", "https", urlparse_cached(response).scheme}+ if self.schemes is None+ else self.schemes+ )all_links = []for doc in docs:links = self._extract_links(doc, response.url, response.encoding, base_url)- all_links.extend(self._process_links(links))+ all_links.extend(self._process_links(links, schemes))if self.link_extractor.unique and len(docs) > 1:return unique_list(all_links, key=self.link_extractor.link_key)return all_linksdiff --git a/scrapy/spiders/sitemap.py b/scrapy/spiders/sitemap.pyindex 85f3fe6a7..647540baa 100644--- a/scrapy/spiders/sitemap.py+++ b/scrapy/spiders/sitemap.py@@ -97,6 +97,17 @@ class SitemapSpider(Spider):``http://example.com/`` would be retrieved."""+ sitemap_schemes: Sequence[str] | None = None+ """URL schemes that the URLs found in sitemaps and :file:`robots.txt` files+ may use.++ .. versionadded:: 2.20.0++ If ``None``, they may only use ``http``, ``https`` or the scheme of the+ sitemap or :file:`robots.txt` file they come from. Use ``()`` to follow+ URLs regardless of their scheme.+ """+_max_size: int_warn_size: int_obey_robotstxt: bool@@ -137,7 +148,9 @@ class SitemapSpider(Spider):# directly instead of stashing them for a response that never arrives.self._signal_only_netlocs.discard(netloc)for url in urls:- if any(x.search(url) for x in self._follow):+ if self._scheme_allowed(url, response.url) and any(+ x.search(url) for x in self._follow+ ):self.crawler.engine.crawl(self.sitemap_request(url,@@ -280,7 +293,8 @@ class SitemapSpider(Spider):response=response,)for url in urls- if any(x.search(url) for x in self._follow)+ if self._scheme_allowed(url, response.url)+ and any(x.search(url) for x in self._follow))body = self._get_sitemap_body(response)@@ -333,7 +347,9 @@ class SitemapSpider(Spider):) -> Iterable[tuple[str, dict[str, Any]]]:for loc, entry in _iterlocs(it, self.sitemap_alternate_links):loc = urljoin(base_url, loc) # noqa: PLW2901- if any(x.search(loc) for x in self._follow):+ if self._scheme_allowed(loc, base_url) and any(+ x.search(loc) for x in self._follow+ ):yield loc, entrydef _get_urls_and_callbacks_from_urlset(@@ -341,11 +357,20 @@ class SitemapSpider(Spider):) -> Iterable[tuple[str, CallbackT, dict[str, Any]]]:for loc, entry in _iterlocs(it, self.sitemap_alternate_links):loc = urljoin(base_url, loc) # noqa: PLW2901+ if not self._scheme_allowed(loc, base_url):+ continuefor r, c in self._cbs:if r.search(loc):yield loc, c, entrybreak+ def _scheme_allowed(self, url: str, source_url: str) -> bool:+ if self.sitemap_schemes is None:+ schemes = {"http", "https", urlparse_cached(source_url).scheme}+ else:+ schemes = set(self.sitemap_schemes)+ return not schemes or urlparse_cached(url).scheme in schemes+def _get_sitemap_body(self, response: Response) -> bytes | None:"""Return the sitemap body contained in the given response,or None if the response is not a sitemap.diff --git a/tests/test_linkextractors.py b/tests/test_linkextractors.pyindex e440b6775..ece65ea19 100644--- a/tests/test_linkextractors.py+++ b/tests/test_linkextractors.py@@ -683,22 +683,30 @@ class TestLxmlLinkExtractor:),]- def test_ftp_links(self):+ @pytest.mark.parametrize(+ ("response_url", "extra_urls"),+ [+ ("http://example.com/index.html", []),+ ("https://example.com/index.html", []),+ ("ftp://example.com/index.html", ["ftp://example.com/d"]),+ ("file:///tmp/index.html", ["file:///etc/passwd"]),+ ],+ )+ def test_default_schemes(self, response_url: str, extra_urls: list[str]) -> None:body = b"""<html><body>- <div><a href="ftp://www.external.com/">An Item</a></div>+ <a href="http://example.com/a">a</a>+ <a href="https://example.com/b">b</a>+ <a href="file:///etc/passwd">c</a>+ <a href="ftp://example.com/d">d</a>+ <a href="s3://bucket/e">e</a>+ <a href="data:text/plain,f">f</a></body></html>"""- response = HtmlResponse(- "http://www.example.com/index.html", body=body, encoding="utf8"- )- lx = LxmlLinkExtractor()- assert lx.extract_links(response) == [- Link(- url="ftp://www.external.com/",- text="An Item",- fragment="",- nofollow=False,- ),+ response = HtmlResponse(response_url, body=body)+ assert [link.url for link in LxmlLinkExtractor().extract_links(response)] == [+ "http://example.com/a",+ "https://example.com/b",+ *extra_urls,]def test_schemes(self):@@ -710,12 +718,6 @@ class TestLxmlLinkExtractor:</body></html>"""response = HtmlResponse("http://www.example.com/index.html", body=body)- lx = LxmlLinkExtractor()- assert lx.extract_links(response) == [- Link(url="http://www.example.com/page.html", text="Page"),- Link(url="data:text/plain,Data", text="Data"),- ]-lx = LxmlLinkExtractor(schemes="mailto")assert lx.extract_links(response) == [Link(url="mailto:[email protected]", text="Mail"),@@ -911,15 +913,15 @@ class TestLxmlLinkExtractor:def test_link_allowed_is_false_with_empty_url(self):bad_link = Link("")- assert not LxmlLinkExtractor()._link_allowed(bad_link)+ assert not LxmlLinkExtractor()._link_allowed(bad_link, {"http", "https"})def test_link_allowed_is_false_with_bad_url_prefix(self):bad_link = Link("htp://should_be_http.example")- assert not LxmlLinkExtractor()._link_allowed(bad_link)+ assert not LxmlLinkExtractor()._link_allowed(bad_link, {"http", "https"})def test_link_allowed_is_false_with_missing_url_prefix(self):bad_link = Link("should_have_prefix.example")- assert not LxmlLinkExtractor()._link_allowed(bad_link)+ assert not LxmlLinkExtractor()._link_allowed(bad_link, {"http", "https"})class TestLxmlParserLinkExtractor:diff --git a/tests/test_spider_sitemap.py b/tests/test_spider_sitemap.pyindex 965543490..e8d840e21 100644--- a/tests/test_spider_sitemap.py+++ b/tests/test_spider_sitemap.py@@ -898,6 +898,137 @@ Sitemap: /sitemap-relative-url.xmlassert request.dont_filter is Falseassert request.callback == spider._parse_sitemap # pylint: disable=comparison-with-callable+ @pytest.mark.parametrize(+ ("schemes", "expected"),+ [+ (None, ["http"]),+ ((), ["file", "http"]),+ (["file"], ["file"]),+ ],+ )+ @coroutine_test+ async def test_sitemap_schemes_urlset(+ self,+ mockserver: MockServer,+ tmp_path: Path,+ schemes: list[str] | None,+ expected: list[str],+ ) -> None:+ page = tmp_path / "page.html"+ page.write_text("<html></html>")+ urls = {"file": page.as_uri(), "http": mockserver.url("/text")}++ class _Spider(RawSitemapSpider, self.spider_class): # type: ignore[name-defined,misc]+ sitemap_schemes = schemes++ def parse(self, response):+ yield {"url": response.url}++ def raw_body(self):+ return (+ '<?xml version="1.0" encoding="UTF-8"?>'+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'+ f"<url><loc>{urls['file']}</loc></url>"+ f"<url><loc>{urls['http']}</loc></url>"+ "</urlset>"+ )++ items, _ = await crawl_items(_Spider, mockserver)+ assert sorted(item["url"] for item in items) == sorted(+ urls[scheme] for scheme in expected+ )++ @pytest.mark.parametrize(("schemes", "followed"), [(None, False), ((), True)])+ @coroutine_test+ async def test_sitemap_schemes_sitemapindex(+ self,+ mockserver: MockServer,+ tmp_path: Path,+ schemes: list[str] | None,+ followed: bool,+ ) -> None:+ sitemap = tmp_path / "sitemap.xml"+ sitemap.write_text(+ '<?xml version="1.0" encoding="UTF-8"?>'+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'+ f"<url><loc>{mockserver.url('/text')}</loc></url>"+ "</urlset>"+ )++ class _Spider(RawSitemapSpider, self.spider_class): # type: ignore[name-defined,misc]+ sitemap_schemes = schemes++ def parse(self, response):+ yield {"url": response.url}++ def raw_body(self):+ return (+ '<?xml version="1.0" encoding="UTF-8"?>'+ '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'+ f"<sitemap><loc>{sitemap.as_uri()}</loc></sitemap>"+ "</sitemapindex>"+ )++ items, _ = await crawl_items(_Spider, mockserver)+ assert items == ([{"url": mockserver.url("/text")}] if followed else [])++ @coroutine_test+ async def test_sitemap_schemes_source_scheme(+ self, mockserver: MockServer, tmp_path: Path+ ) -> None:+ page = tmp_path / "page.html"+ page.write_text("<html></html>")+ sitemap = tmp_path / "sitemap.xml"+ sitemap.write_text(+ '<?xml version="1.0" encoding="UTF-8"?>'+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'+ f"<url><loc>{page.as_uri()}</loc></url>"+ "</urlset>"+ )++ class _Spider(self.spider_class): # type: ignore[name-defined,misc]+ name = "test"+ sitemap_urls = [sitemap.as_uri()]++ def parse(self, response):+ yield {"url": response.url}++ items, _ = await crawl_items(_Spider, mockserver)+ assert items == [{"url": page.as_uri()}]++ def test_sitemap_schemes_robotstxt(self):+ robots = (+ b"Sitemap: file:///etc/sitemap.xml\n"+ b"Sitemap: ftp://example.com/sitemap.xml\n"+ b"Sitemap: https://example.com/sitemap.xml\n"+ )+ r = TextResponse(url="http://www.example.com/robots.txt", body=robots)+ spider = self.spider_class("example.com")+ assert [req.url for req in spider._parse_sitemap(r)] == [+ "https://example.com/sitemap.xml",+ ]++ def test_sitemap_schemes_robots_parsed_signal(self):+ crawler = get_crawler(self.spider_class, settings_dict={"ROBOTSTXT_OBEY": True})+ spider = self.spider_class.from_crawler(crawler, "example.com")+ crawler.engine = mock.MagicMock()+ spider._signal_only_netlocs.add("www.example.com")++ class FakeRobotParser:+ def sitemaps(self):+ return ["file:///etc/sitemap.xml", "/sitemap.xml"]++ crawler.signals.send_catch_log(+ signal=signals.robots_parsed,+ robotparser=FakeRobotParser(),+ request=Request("http://www.example.com/some/page"),+ response=TextResponse("http://www.example.com/robots.txt"),+ )++ crawler.engine.crawl.assert_called_once()+ scheduled = crawler.engine.crawl.call_args[0][0]+ assert scheduled.url == "http://www.example.com/sitemap.xml"+def test_iterloc_deprecated():entries = [{"loc": "http://www.example.com/"}]