Scrapy, a fast high-level web crawling & scraping framework for Python.
Support --curl in commands (#7703)
Adrian64b3f965d058
diff --git a/docs/topics/commands.rst b/docs/topics/commands.rstindex b9b7c2a31..1d56ee0aa 100644--- a/docs/topics/commands.rst+++ b/docs/topics/commands.rst@@ -462,11 +462,21 @@ Supported options:* ``--no-redirect``: do not follow HTTP 3xx redirects (default is to follow them)+* ``--curl=COMMAND``: build the request from a `cURL`_ command instead of from a+ URL argument, taking the URL, HTTP method, headers, cookies and body from the+ command (see :meth:`Request.from_curl() <scrapy.Request.from_curl>`). It cannot+ be combined with a URL argument.++ .. versionadded:: VERSION+Usage examples::$ scrapy fetch --nolog http://www.example.com/some/page.html[ ... html content here ... ]+ $ scrapy fetch --nolog --curl 'curl -d title=hello https://httpbin.org/post'+ [ ... html content here ... ]+$ scrapy fetch --nolog --headers http://www.example.com/> Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8> Accept-Language: en@@ -500,6 +510,12 @@ Supported options:* ``--no-redirect``: do not follow HTTP 3xx redirects (default is to follow them)+* ``--curl=COMMAND``: build the request from a `cURL`_ command instead of from a+ URL argument (see :meth:`Request.from_curl() <scrapy.Request.from_curl>`). It+ cannot be combined with a URL argument.++ .. versionadded:: VERSION+Usage example::$ scrapy view http://www.example.com/some/page.html@@ -528,6 +544,12 @@ Supported options:this only affects the URL you may pass as argument on the command line;once you are inside the shell, ``fetch(url)`` will still follow HTTP redirects by default.+* ``--curl=COMMAND``: build the request from a `cURL`_ command instead of from a+ URL argument (see :meth:`Request.from_curl() <scrapy.Request.from_curl>`). It+ cannot be combined with a URL argument.++ .. versionadded:: VERSION+Usage example::$ scrapy shell http://www.example.com/some/page.html@@ -566,6 +588,12 @@ Supported options:* ``--callback`` or ``-c``: spider method to use as callback for parsing theresponse+* ``--curl=COMMAND``: build the request from a `cURL`_ command instead of from a+ URL argument (see :meth:`Request.from_curl() <scrapy.Request.from_curl>`). It+ cannot be combined with a URL argument.++ .. versionadded:: VERSION+* ``--meta`` or ``-m``: additional request meta that will be passed to thecallback request. This must be a valid JSON string. Example:``--meta='{"foo": "bar"}'``@@ -877,3 +905,5 @@ Example:.. code-block:: pythonCOMMANDS_MODULE = "mybot.commands"++.. _cURL: https://curl.se/diff --git a/scrapy/commands/__init__.py b/scrapy/commands/__init__.pyindex c87c390c1..7805d5e2c 100644--- a/scrapy/commands/__init__.py+++ b/scrapy/commands/__init__.py@@ -17,6 +17,7 @@ from typing import TYPE_CHECKING, Any, ClassVarfrom scrapy import signalsfrom scrapy.exceptions import ScrapyDeprecationWarning, UsageErrorfrom scrapy.extensions.feedexport import FeedExporter+from scrapy.http import Requestfrom scrapy.utils.conf import arglist_to_dict, feed_process_params_from_clifrom scrapy.utils.deprecate import method_is_overriddenfrom scrapy.utils.python import global_object_name@@ -32,6 +33,27 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+def _add_curl_option(parser: argparse.ArgumentParser) -> None:+ """Register the ``--curl`` option on commands that accept a URL."""+ parser.add_argument(+ "--curl",+ metavar="COMMAND",+ default=None,+ help="build the request from a curl command, e.g. "+ "--curl 'curl -d a=1 https://example.com'; cannot be combined "+ "with a URL argument",+ )+++def _request_from_curl(curl_command: str, **kwargs: Any) -> Request:+ """Build a :class:`~scrapy.Request` from a curl command, reporting parsing+ errors as :exc:`~scrapy.exceptions.UsageError`."""+ try:+ return Request.from_curl(curl_command, **kwargs)+ except ValueError as e:+ raise UsageError(str(e), print_help=False) from e++class _PdbHandler(logging.Handler):"""Start a post-mortem debugging session on every logged record that comeswith an exception traceback."""diff --git a/scrapy/commands/fetch.py b/scrapy/commands/fetch.pyindex c345e297c..a5b44c562 100644--- a/scrapy/commands/fetch.py+++ b/scrapy/commands/fetch.py@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Anyfrom w3lib.url import is_url-from scrapy.commands import ScrapyCommand+from scrapy.commands import ScrapyCommand, _add_curl_option, _request_from_curlfrom scrapy.exceptions import UsageErrorfrom scrapy.http import Request, Responsefrom scrapy.utils._datatypes import SequenceExclude@@ -34,6 +34,7 @@ class Command(ScrapyCommand):def add_options(self, parser: ArgumentParser) -> None:super().add_options(parser)+ _add_curl_option(parser)parser.add_argument("--spider", dest="spider", help="use this spider")parser.add_argument("--headers",@@ -67,14 +68,24 @@ class Command(ScrapyCommand):sys.stdout.buffer.write(bytes_ + b"\n")def run(self, args: list[str], opts: Namespace) -> None:- if len(args) != 1 or not is_url(args[0]):- raise UsageError- request = Request(- args[0],- callback=self._print_response,- cb_kwargs={"opts": opts},- dont_filter=True,- )+ if opts.curl:+ if args:+ raise UsageError("--curl cannot be combined with a URL argument")+ request = _request_from_curl(+ opts.curl,+ callback=self._print_response,+ cb_kwargs={"opts": opts},+ dont_filter=True,+ )+ else:+ if len(args) != 1 or not is_url(args[0]):+ raise UsageError+ request = Request(+ args[0],+ callback=self._print_response,+ cb_kwargs={"opts": opts},+ dont_filter=True,+ )# by default, let the framework handle redirects,# i.e. command handles all codes expect 3xxif not opts.no_redirect:diff --git a/scrapy/commands/parse.py b/scrapy/commands/parse.pyindex 4edadfa58..be84af063 100644--- a/scrapy/commands/parse.py+++ b/scrapy/commands/parse.py@@ -10,7 +10,7 @@ from itemadapter import ItemAdapterfrom twisted.internet.defer import Deferred, maybeDeferredfrom w3lib.url import is_url-from scrapy.commands import BaseRunSpiderCommand+from scrapy.commands import BaseRunSpiderCommand, _add_curl_option, _request_from_curlfrom scrapy.exceptions import UsageErrorfrom scrapy.http import Request, Responsefrom scrapy.utils import _colorize@@ -53,6 +53,7 @@ class Command(BaseRunSpiderCommand):def add_options(self, parser: argparse.ArgumentParser) -> None:super().add_options(parser)+ _add_curl_option(parser)parser.add_argument("--spider",dest="spider",@@ -242,7 +243,7 @@ class Command(BaseRunSpiderCommand):)return None- def set_spidercls(self, url: str, opts: argparse.Namespace) -> None:+ def set_spidercls(self, request: Request, opts: argparse.Namespace) -> None:assert self.crawler_processspider_loader = self.crawler_process.spider_loaderif opts.spider:@@ -253,12 +254,12 @@ class Command(BaseRunSpiderCommand):"Unable to find spider: %(spider)s", {"spider": opts.spider})else:- self.spidercls = spidercls_for_request(spider_loader, Request(url))+ self.spidercls = spidercls_for_request(spider_loader, request)if not self.spidercls:- logger.error("Unable to find spider for: %(url)s", {"url": url})+ logger.error("Unable to find spider for: %(url)s", {"url": request.url})async def start(spider: Spider) -> AsyncIterator[Any]:- yield self.prepare_request(spider, Request(url), opts)+ yield self.prepare_request(spider, request, opts)if self.spidercls:self.spidercls.start = start # type: ignore[assignment,method-assign]@@ -404,12 +405,18 @@ class Command(BaseRunSpiderCommand):def run(self, args: list[str], opts: argparse.Namespace) -> None:# parse arguments- if not len(args) == 1 or not is_url(args[0]):- raise UsageError- url = args[0]+ if opts.curl:+ if args:+ raise UsageError("--curl cannot be combined with a URL argument")+ request = _request_from_curl(opts.curl)+ else:+ if not len(args) == 1 or not is_url(args[0]):+ raise UsageError+ request = Request(args[0])+ url = request.url# prepare spidercls- self.set_spidercls(url, opts)+ self.set_spidercls(request, opts)if self.spidercls and opts.depth > 0:self.start_parsing(url, opts)diff --git a/scrapy/commands/shell.py b/scrapy/commands/shell.pyindex f64f557b5..4caa43719 100644--- a/scrapy/commands/shell.py+++ b/scrapy/commands/shell.py@@ -10,11 +10,13 @@ import asynciofrom threading import Threadfrom typing import TYPE_CHECKING, Any, ClassVar-from scrapy.commands import ScrapyCommand+from scrapy.commands import ScrapyCommand, _add_curl_option, _request_from_curlfrom scrapy.core.engine import ExecutionEnginefrom scrapy.crawler import AsyncCrawlerProcess, Crawler+from scrapy.exceptions import UsageErrorfrom scrapy.http import Requestfrom scrapy.shell import Shell+from scrapy.utils.datatypes import SequenceExcludefrom scrapy.utils.spider import DefaultSpider, spidercls_for_requestfrom scrapy.utils.url import guess_scheme@@ -46,6 +48,7 @@ class Command(ScrapyCommand):def add_options(self, parser: ArgumentParser) -> None:super().add_options(parser)+ _add_curl_option(parser)parser.add_argument("-c",dest="code",@@ -67,7 +70,19 @@ class Command(ScrapyCommand):def run(self, args: list[str], opts: Namespace) -> None:url = args[0] if args else None- if url:+ request: Request | None = None+ if opts.curl:+ if url:+ raise UsageError("--curl cannot be combined with a URL argument")+ request = _request_from_curl(opts.curl, dont_filter=True)+ if opts.no_redirect:+ request.meta["handle_httpstatus_all"] = True+ else:+ request.meta["handle_httpstatus_list"] = SequenceExclude(+ range(300, 400)+ )+ url = request.url+ elif url:# first argument may be a local fileurl = guess_scheme(url)@@ -77,6 +92,10 @@ class Command(ScrapyCommand):spidercls: type[Spider] = DefaultSpiderif opts.spider:spidercls = spider_loader.load(opts.spider)+ elif request is not None:+ spidercls = spidercls_for_request(+ spider_loader, request, spidercls, log_multiple=True+ )elif url:spidercls = spidercls_for_request(spider_loader, Request(url), spidercls, log_multiple=True@@ -93,7 +112,10 @@ class Command(ScrapyCommand):self._init_without_reactor(crawler)loop = self._get_reactorless_loop()shell = Shell(crawler, update_vars=self.update_vars, code=opts.code, loop=loop)- shell.start(url=url, redirect=not opts.no_redirect)+ if request is not None:+ shell.start(request=request, redirect=not opts.no_redirect)+ else:+ shell.start(url=url, redirect=not opts.no_redirect)def _init_with_reactor(self, crawler: Crawler) -> None:# Create the engine in the main threaddiff --git a/tests/test_command_fetch.py b/tests/test_command_fetch.pyindex e25540f50..bf239b34b 100644--- a/tests/test_command_fetch.py+++ b/tests/test_command_fetch.py@@ -1,5 +1,6 @@from __future__ import annotations+import jsonfrom typing import TYPE_CHECKINGimport pytest@@ -48,6 +49,23 @@ class TestFetchCommand:)assert out.strip() == "Works"+ def test_curl(self, mockserver: MockServer) -> None:+ url = mockserver.url("/echo")+ _, out, _ = proc("fetch", "--curl", f"curl -d a=1 -H 'X-Test: foo' {url}")+ echo = json.loads(out)+ assert echo["body"] == "a=1"+ assert echo["headers"]["X-Test"] == ["foo"]++ def test_curl_with_url(self, mockserver: MockServer) -> None:+ url = mockserver.url("/echo")+ code, _, _ = proc("fetch", "--curl", f"curl {url}", url)+ assert code != 0++ def test_curl_invalid(self) -> None:+ code, _, err = proc("fetch", "--curl", "not-a-curl-command")+ assert code != 0+ assert "curl" in err+class TestFetchCommandWithSpider(TestProjectBase):@pytest.fixture(autouse=True)diff --git a/tests/test_command_parse.py b/tests/test_command_parse.pyindex f06816b8c..663ea5799 100644--- a/tests/test_command_parse.py+++ b/tests/test_command_parse.py@@ -239,6 +239,41 @@ ITEM_PIPELINES = {{'{self.project_name}.pipelines.MyPipeline': 1}})assert "DEBUG: It Works!" in stderr+ def test_invalid_url(self, proj_path: Path) -> None:+ code, _, _ = proc(+ "parse", "--spider", self.spider_name, "not-a-url", cwd=proj_path+ )+ assert code != 0++ def test_curl(self, proj_path: Path, mockserver: MockServer) -> None:+ _, _, stderr = proc(+ "parse",+ "--spider",+ self.spider_name,+ "-a",+ "test_arg=1",+ "--curl",+ f"curl {mockserver.url('/html')}",+ "-c",+ "parse",+ "--verbose",+ cwd=proj_path,+ )+ assert "DEBUG: It Works!" in stderr++ def test_curl_with_url(self, proj_path: Path, mockserver: MockServer) -> None:+ url = mockserver.url("/html")+ code, _, _ = proc(+ "parse",+ "--spider",+ self.spider_name,+ "--curl",+ f"curl {url}",+ url,+ cwd=proj_path,+ )+ assert code != 0+def test_request_with_meta(self, proj_path: Path, mockserver: MockServer) -> None:raw_json_string = '{"foo" : "baz"}'_, _, stderr = proc(diff --git a/tests/test_command_shell.py b/tests/test_command_shell.pyindex a483f5abd..dc156947a 100644--- a/tests/test_command_shell.py+++ b/tests/test_command_shell.py@@ -43,6 +43,34 @@ class TestShellCommand:_, out, _ = proc("shell", mockserver.url("/text"), "-c", "response.body")assert "Works" in out+ def test_curl(self, mockserver: MockServer) -> None:+ url = mockserver.url("/echo")+ _, out, _ = proc(+ "shell",+ "--curl",+ f"curl -d a=1 {url}",+ "-c",+ "(request.method, request.body)",+ )+ assert "('POST', b'a=1')" in out++ def test_curl_no_redirect(self, mockserver: MockServer) -> None:+ url = mockserver.url("/redirect-no-meta-refresh")+ _, out, _ = proc(+ "shell",+ "--no-redirect",+ "--curl",+ f"curl {url}",+ "-c",+ "response.status",+ )+ assert out.strip().endswith("302")++ def test_curl_with_url(self, mockserver: MockServer) -> None:+ url = mockserver.url("/echo")+ code, _, _ = proc("shell", "--curl", f"curl {url}", url, "-c", "url")+ assert code != 0+def test_response_type_text(self, mockserver: MockServer) -> None:_, out, _ = proc("shell", mockserver.url("/text"), "-c", "type(response)")assert "TextResponse" in out