Skip to content

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

Support FTP directory listing via trailing slash in URL (#8197)

Adriana951e1f961f9
diff --git a/docs/topics/download-handlers.rst b/docs/topics/download-handlers.rst
index 4209385f0..b3ab386a7 100644
--- a/docs/topics/download-handlers.rst
+++ b/docs/topics/download-handlers.rst
@@ -447,6 +447,10 @@ This handler supports ``ftp://host/path`` FTP URIs.
It's implemented using :mod:`twisted.protocols.ftp`.
+A path ending in ``/`` is listed instead of downloaded. The response
+body is the plain-text output of the FTP ``NLST`` command, one file or
+directory name per line.
+
.. _s3-handler:
S3DownloadHandler
diff --git a/scrapy/core/downloader/handlers/ftp.py b/scrapy/core/downloader/handlers/ftp.py
index 05bd0ee5d..327193a29 100644
--- a/scrapy/core/downloader/handlers/ftp.py
+++ b/scrapy/core/downloader/handlers/ftp.py
@@ -109,9 +109,13 @@ class FTPDownloadHandler(BaseDownloadHandler):
creator.connectTCP(parsed_url.hostname, parsed_url.port or 21)
)
filepath = unquote(parsed_url.path)
+ is_listing = filepath == "" or filepath.endswith("/")
protocol = ReceivedDataProtocol(request.meta.get("ftp_local_filename"))
try:
- await maybe_deferred_to_future(client.retrieveFile(filepath, protocol))
+ if is_listing:
+ await maybe_deferred_to_future(client.nlst(filepath, protocol))
+ else:
+ await maybe_deferred_to_future(client.retrieveFile(filepath, protocol))
except CommandFailed as e:
message = str(e)
# Twisted only raises CommandFailed for a reply whose numeric code
diff --git a/tests/test_downloader_handler_twisted_ftp.py b/tests/test_downloader_handler_twisted_ftp.py
index fb75a618b..bea4d44a5 100644
--- a/tests/test_downloader_handler_twisted_ftp.py
+++ b/tests/test_downloader_handler_twisted_ftp.py
@@ -109,6 +109,24 @@ class TestFTPBase(ABC):
assert r.status == 404
assert r.body == b"['550 nonexistent.txt: No such file or directory.']"
+ @deferred_f_from_coro_f
+ async def test_ftp_list(self, server_url: str, dh: FTPDownloadHandler) -> None:
+ request = Request(url=server_url, meta=self.req_meta)
+ r = await dh.download_request(request)
+ assert isinstance(r, TextResponse)
+ assert r.status == 200
+ assert set(r.text.splitlines()) == {filename for filename, _ in self.test_files}
+
+ @deferred_f_from_coro_f
+ async def test_ftp_list_nonexistent(
+ self, server_url: str, dh: FTPDownloadHandler
+ ) -> None:
+ request = Request(url=server_url + "nonexistent/", meta=self.req_meta)
+ r = await dh.download_request(request)
+ assert isinstance(r, TextResponse)
+ assert r.status == 200
+ assert r.text == ""
+
@deferred_f_from_coro_f
async def test_ftp_local_filename(
self, server_url: str, dh: FTPDownloadHandler