-
Notifications
You must be signed in to change notification settings - Fork 397
feat: add an internal HttpClient
to be used in send_request
for PlaywrightCrawler
using APIRequestContext
bound to the browser context
#1134
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+219
−47
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
86325a9
add helper function `send_request` for playwright
Mantisus b8aaa60
resolve
Mantisus 88a722b
resolve
Mantisus fa532d1
change helper to inner http-client
Mantisus 25d1cb3
update docs
Mantisus 35c9d6b
add comments
Mantisus 89504fe
add contextmanager for managment ContextVar
Mantisus fe08a28
resolve
Mantisus 5ce3320
workaround for robots.txt requests
Mantisus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
91 changes: 91 additions & 0 deletions
91
src/crawlee/crawlers/_playwright/_playwright_http_client.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
from __future__ import annotations | ||
|
||
import contextvars | ||
from contextlib import asynccontextmanager | ||
from typing import TYPE_CHECKING | ||
|
||
from typing_extensions import override | ||
|
||
from crawlee._types import HttpHeaders | ||
from crawlee.crawlers._playwright._types import PlaywrightHttpResponse | ||
from crawlee.http_clients import HttpClient, HttpCrawlingResult, HttpResponse | ||
|
||
if TYPE_CHECKING: | ||
from collections.abc import AsyncGenerator | ||
|
||
from playwright.async_api import Page | ||
|
||
from crawlee import Request | ||
from crawlee._types import HttpMethod, HttpPayload | ||
from crawlee.proxy_configuration import ProxyInfo | ||
from crawlee.sessions import Session | ||
from crawlee.statistics import Statistics | ||
|
||
|
||
_browser_page_context_var: contextvars.ContextVar[Page | None] = contextvars.ContextVar('browser_context', default=None) | ||
|
||
|
||
@asynccontextmanager | ||
async def browser_page_context(page: Page) -> AsyncGenerator[None, None]: | ||
"""Asynchronous context manager for setting the current Playwright page in the context variable.""" | ||
token = _browser_page_context_var.set(page) | ||
try: | ||
yield | ||
finally: | ||
_browser_page_context_var.reset(token) | ||
|
||
|
||
class PlaywrightHttpClient(HttpClient): | ||
"""HTTP client based on the Playwright library. | ||
|
||
This client uses the Playwright library to perform HTTP requests in crawlers (`BasicCrawler` subclasses) | ||
and to manage sessions, proxies, and error handling. | ||
|
||
See the `HttpClient` class for more common information about HTTP clients. | ||
|
||
Note: This class is pre-designated for use in `PlaywrightCrawler` only | ||
""" | ||
|
||
def __init__(self) -> None: | ||
"""Initialize a new instance.""" | ||
|
||
@override | ||
async def crawl( | ||
self, | ||
request: Request, | ||
*, | ||
session: Session | None = None, | ||
proxy_info: ProxyInfo | None = None, | ||
statistics: Statistics | None = None, | ||
) -> HttpCrawlingResult: | ||
raise NotImplementedError('The `crawl` method should not be used for `PlaywrightHttpClient`') | ||
|
||
@override | ||
async def send_request( | ||
self, | ||
url: str, | ||
*, | ||
method: HttpMethod = 'GET', | ||
headers: HttpHeaders | dict[str, str] | None = None, | ||
payload: HttpPayload | None = None, | ||
session: Session | None = None, | ||
proxy_info: ProxyInfo | None = None, | ||
) -> HttpResponse: | ||
# `proxy_info` are not used because `APIRequestContext` inherits the proxy from `BrowserContext` | ||
# TODO: Use `session` to restore all the fingerprint headers according to the `BrowserContext`, after resolved | ||
# https://github.com/apify/crawlee-python/issues/1055 | ||
|
||
if isinstance(headers, dict) or headers is None: | ||
headers = HttpHeaders(headers or {}) | ||
|
||
browser_context = _browser_page_context_var.get() | ||
|
||
if browser_context is None: | ||
raise RuntimeError('Unable to create an `APIRequestContext` outside the browser context') | ||
|
||
# Proxies appropriate to the browser context are used | ||
response = await browser_context.request.fetch( | ||
url_or_request=url, method=method.lower(), headers=dict(headers) if headers else None, data=payload | ||
) | ||
|
||
return await PlaywrightHttpResponse.from_playwright_response(response, protocol='') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
janbuchar marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.