Skip to content

Commit 6d23d0e

Browse files
committed
Override method and/or body only for the first matching request
1 parent f3b1b25 commit 6d23d0e

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

scrapy_playwright/handler.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,13 @@ async def _download_request(self, request: Request, spider: Spider) -> Response:
357357
page=page, request=request, spider=spider, context_name=context_name
358358
)
359359

360+
# We need to identify the Playwright request that matches the Scrapy request
361+
# in order to override method and body if necessary.
362+
# Checking the URL and Request.is_navigation_request() is not enough, e.g.
363+
# requests produced by submitting forms can produce false positives.
364+
# Let's track only the first request that matches the above conditions.
365+
initial_request_done = asyncio.Event()
366+
360367
await page.unroute("**")
361368
await page.route(
362369
"**",
@@ -368,6 +375,7 @@ async def _download_request(self, request: Request, spider: Spider) -> Response:
368375
body=request.body,
369376
encoding=request.encoding,
370377
spider=spider,
378+
initial_request_done=initial_request_done,
371379
),
372380
)
373381

@@ -637,6 +645,7 @@ def _make_request_handler(
637645
body: Optional[bytes],
638646
encoding: str,
639647
spider: Spider,
648+
initial_request_done: asyncio.Event,
640649
) -> Callable:
641650
async def _request_handler(route: Route, playwright_request: PlaywrightRequest) -> None:
642651
"""Override request headers, method and body."""
@@ -676,7 +685,9 @@ async def _request_handler(route: Route, playwright_request: PlaywrightRequest)
676685
if (
677686
playwright_request.url.rstrip("/") == url.rstrip("/")
678687
and playwright_request.is_navigation_request()
688+
and not initial_request_done.is_set()
679689
):
690+
initial_request_done.set()
680691
if method.upper() != playwright_request.method.upper():
681692
overrides["method"] = method
682693
if body:

0 commit comments

Comments
 (0)