diff --git a/scrapling/core/shell.py b/scrapling/core/shell.py index a70458b..07a38aa 100644 --- a/scrapling/core/shell.py +++ b/scrapling/core/shell.py @@ -30,7 +30,7 @@ from scrapling.core._types import List, Optional, Dict, Tuple, Any, Union from scrapling.fetchers import ( Fetcher, AsyncFetcher, - PlayWrightFetcher, + DynamicFetcher, StealthyFetcher, Response, ) @@ -436,7 +436,7 @@ class CustomShell: return f""" -> Available Scrapling objects: - Fetcher/AsyncFetcher - - PlayWrightFetcher + - DynamicFetcher - StealthyFetcher - Adaptor @@ -445,7 +445,7 @@ class CustomShell: - {"post":<30} Shortcut for `Fetcher.post` - {"put":<30} Shortcut for `Fetcher.put` - {"delete":<30} Shortcut for `Fetcher.delete` - - {"fetch":<30} Shortcut for `PlayWrightFetcher.fetch` + - {"fetch":<30} Shortcut for `DynamicFetcher.fetch` - {"stealthy_fetch":<30} Shortcut for `StealthyFetcher.fetch` -> Useful commands @@ -493,7 +493,7 @@ Type 'exit' or press Ctrl+D to exit. post = self.create_wrapper(Fetcher.post) put = self.create_wrapper(Fetcher.put) delete = self.create_wrapper(Fetcher.delete) - dynamic_fetch = self.create_wrapper(PlayWrightFetcher.fetch) + dynamic_fetch = self.create_wrapper(DynamicFetcher.fetch) stealthy_fetch = self.create_wrapper(StealthyFetcher.fetch) curl2fetcher = self.create_wrapper(self._curl_parser.convert2fetcher) @@ -506,7 +506,7 @@ Type 'exit' or press Ctrl+D to exit. "Fetcher": Fetcher, "AsyncFetcher": AsyncFetcher, "fetch": dynamic_fetch, - "PlayWrightFetcher": PlayWrightFetcher, + "DynamicFetcher": DynamicFetcher, "stealthy_fetch": stealthy_fetch, "StealthyFetcher": StealthyFetcher, "Adaptor": Adaptor, diff --git a/scrapling/engines/__init__.py b/scrapling/engines/__init__.py index 5d0c240..9ebf5e9 100644 --- a/scrapling/engines/__init__.py +++ b/scrapling/engines/__init__.py @@ -1,7 +1,7 @@ from .camo import CamoufoxEngine from .constants import DEFAULT_DISABLED_RESOURCES, DEFAULT_STEALTH_FLAGS -from .pw import PlaywrightEngine from .static import FetcherSession, FetcherClient, AsyncFetcherClient from .toolbelt import check_if_engine_usable +from ._browsers import DynamicSession, AsyncDynamicSession -__all__ = ["CamoufoxEngine", "PlaywrightEngine"] +__all__ = ["FetcherSession", "DynamicSession", "AsyncDynamicSession"] diff --git a/scrapling/engines/pw.py b/scrapling/engines/pw.py deleted file mode 100644 index 5b13fab..0000000 --- a/scrapling/engines/pw.py +++ /dev/null @@ -1,402 +0,0 @@ -import json - -from playwright.sync_api import sync_playwright -from playwright.async_api import async_playwright -from playwright.sync_api import Response as SyncPlaywrightResponse -from playwright.async_api import Response as AsyncPlaywrightResponse -from rebrowser_playwright.sync_api import sync_playwright as sync_rebrowser_playwright -from rebrowser_playwright.async_api import ( - async_playwright as async_rebrowser_playwright, -) - -from scrapling.core._types import ( - Callable, - Dict, - Optional, - SelectorWaitStates, - Union, - Iterable, -) -from scrapling.core.utils import log, lru_cache -from scrapling.engines.constants import DEFAULT_STEALTH_FLAGS, NSTBROWSER_DEFAULT_QUERY -from scrapling.engines.toolbelt import ( - Response, - ResponseFactory, - async_intercept_route, - check_type_validity, - construct_cdp_url, - construct_proxy_dict, - generate_convincing_referer, - generate_headers, - intercept_route, - js_bypass_path, -) - - -class PlaywrightEngine: - def __init__( - self, - headless: Union[bool, str] = True, - disable_resources: bool = False, - useragent: Optional[str] = None, - network_idle: bool = False, - timeout: Optional[float] = 30000, - wait: Optional[int] = 0, - page_action: Callable = None, - wait_selector: Optional[str] = None, - locale: Optional[str] = "en-US", - wait_selector_state: SelectorWaitStates = "attached", - cookies: Optional[Iterable[Dict]] = None, - stealth: bool = False, - real_chrome: bool = False, - hide_canvas: bool = False, - disable_webgl: bool = False, - cdp_url: Optional[str] = None, - nstbrowser_mode: bool = False, - nstbrowser_config: Optional[Dict] = None, - google_search: bool = True, - extra_headers: Optional[Dict[str, str]] = None, - proxy: Optional[Union[str, Dict[str, str]]] = None, - adaptor_arguments: Dict = None, - ): - """An engine that uses the PlayWright library checks the `PlayWrightFetcher` class for more documentation. - - :param headless: Run the browser in headless/hidden (default), or headful/visible mode. - :param disable_resources: Drop requests of unnecessary resources for a speed boost. It depends, but it made requests ~25% faster in my tests for some websites. - Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`. - This can help save your proxy usage but be careful with this option as it makes some websites never finish loading. - :param useragent: Pass a useragent string to be used. Otherwise the fetcher will generate a real Useragent of the same browser and use it. - :param cookies: Set cookies for the next request. - :param network_idle: Wait for the page until there are no network connections for at least 500 ms. - :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000 - :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the ` Response ` object. - :param page_action: Added for automation. A function that takes the `page` object, does the automation you need, then returns `page` again. - :param wait_selector: Wait for a specific CSS selector to be in a specific state. - :param locale: Set the locale for the browser if wanted. The default value is `en-US`. - :param wait_selector_state: The state to wait for the selector given with `wait_selector`. The default state is `attached`. - :param stealth: Enables stealth mode, check the documentation to see what stealth mode does currently. - :param real_chrome: If you have a Chrome browser installed on your device, enable this, and the Fetcher will launch an instance of your browser and use it. - :param hide_canvas: Add random noise to canvas operations to prevent fingerprinting. - :param disable_webgl: Disables WebGL and WebGL 2.0 support entirely. - :param cdp_url: Instead of launching a new browser instance, connect to this CDP URL to control real browsers/NSTBrowser through CDP. - :param nstbrowser_mode: Enables NSTBrowser mode, it has to be used with the ` cdp_url ` argument, or it will get completely ignored. - :param google_search: Enabled by default, Scrapling will set the referer header to be as if this request came from a Google search for this website's domain name. - :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by the `google_search` argument takes priority over the referer set here if used together._ - :param proxy: The proxy to be used with requests, it can be a string or a dictionary with the keys 'server', 'username', and 'password' only. - :param nstbrowser_config: The config you want to send with requests to the NSTBrowser. If left empty, Scrapling defaults to an optimized NSTBrowser's docker browserless config. - :param adaptor_arguments: The arguments that will be passed in the end while creating the final Adaptor's class. - """ - self.headless = headless - self.locale = check_type_validity(locale, [str], "en-US", param_name="locale") - self.disable_resources = disable_resources - self.network_idle = bool(network_idle) - self.stealth = bool(stealth) - self.hide_canvas = bool(hide_canvas) - self.disable_webgl = bool(disable_webgl) - self.real_chrome = bool(real_chrome) - self.google_search = bool(google_search) - self.extra_headers = extra_headers or {} - self.proxy = construct_proxy_dict(proxy) - self.cdp_url = cdp_url - self.useragent = useragent - self.cookies = cookies or [] - self.timeout = check_type_validity(timeout, [int, float], 30000) - self.wait = check_type_validity(wait, [int, float], 0) - if page_action is not None: - if callable(page_action): - self.page_action = page_action - else: - self.page_action = None - log.error('[Ignored] Argument "page_action" must be callable') - else: - self.page_action = None - - self.wait_selector = wait_selector - self.wait_selector_state = wait_selector_state - self.nstbrowser_mode = bool(nstbrowser_mode) - self.nstbrowser_config = nstbrowser_config - self.adaptor_arguments = adaptor_arguments if adaptor_arguments else {} - self.harmful_default_args = [ - # This will be ignored to avoid detection more and possibly avoid the popup crashing bug abuse: https://issues.chromium.org/issues/340836884 - "--enable-automation", - "--disable-popup-blocking", - # '--disable-component-update', - # '--disable-default-apps', - # '--disable-extensions', - ] - - def _cdp_url_logic(self) -> str: - """Constructs a new CDP URL if NSTBrowser is enabled otherwise return CDP URL as it is - :return: CDP URL - """ - cdp_url = self.cdp_url - if self.nstbrowser_mode: - if self.nstbrowser_config and isinstance(self.nstbrowser_config, dict): - config = self.nstbrowser_config - else: - query = NSTBROWSER_DEFAULT_QUERY.copy() - if self.stealth: - flags = self.__set_flags() - query.update( - { - "args": dict( - zip(flags, [""] * len(flags)) - ), # browser args should be a dictionary - } - ) - - config = { - "config": json.dumps(query), - # 'token': '' - } - cdp_url = construct_cdp_url(cdp_url, config) - else: - # To validate it - cdp_url = construct_cdp_url(cdp_url) - - return cdp_url - - @lru_cache(32, typed=True) - def __set_flags(self): - """Returns the flags that will be used while launching the browser if stealth mode is enabled""" - flags = DEFAULT_STEALTH_FLAGS - if self.hide_canvas: - flags += ("--fingerprinting-canvas-image-data-noise",) - if self.disable_webgl: - flags += ( - "--disable-webgl", - "--disable-webgl-image-chromium", - "--disable-webgl2", - ) - - return flags - - def __launch_kwargs(self): - """Creates the arguments we will use while launching playwright's browser""" - launch_kwargs = { - "headless": self.headless, - "ignore_default_args": self.harmful_default_args, - "channel": "chrome" if self.real_chrome else "chromium", - } - if self.stealth: - launch_kwargs.update({"args": self.__set_flags(), "chromium_sandbox": True}) - - return launch_kwargs - - def __context_kwargs(self): - """Creates the arguments for the browser context""" - context_kwargs = { - "proxy": self.proxy, - "locale": self.locale, - "color_scheme": "dark", # Bypasses the 'prefersLightColor' check in creepjs - "device_scale_factor": 2, - "extra_http_headers": self.extra_headers if self.extra_headers else {}, - "user_agent": self.useragent - if self.useragent - else generate_headers(browser_mode=True).get("User-Agent"), - } - if self.stealth: - context_kwargs.update( - { - "is_mobile": False, - "has_touch": False, - # I'm thinking about disabling it to rest from all Service Workers headache, but let's keep it as it is for now - "service_workers": "allow", - "ignore_https_errors": True, - "screen": {"width": 1920, "height": 1080}, - "viewport": {"width": 1920, "height": 1080}, - "permissions": ["geolocation", "notifications"], - } - ) - - return context_kwargs - - @lru_cache(1) - def __stealth_scripts(self): - # Basic bypasses nothing fancy as I'm still working on it - # But with adding these bypasses to the above config, it bypasses many online tests like - # https://bot.sannysoft.com/ - # https://kaliiiiiiiiii.github.io/brotector/ - # https://pixelscan.net/ - # https://iphey.com/ - # https://www.browserscan.net/bot-detection <== this one also checks for the CDP runtime fingerprint - # https://arh.antoinevastel.com/bots/areyouheadless/ - # https://prescience-data.github.io/execution-monitor.html - return tuple( - js_bypass_path(script) - for script in ( - # Order is important - "webdriver_fully.js", - "window_chrome.js", - "navigator_plugins.js", - "pdf_viewer.js", - "notification_permission.js", - "screen_props.js", - "playwright_fingerprint.js", - ) - ) - - def fetch(self, url: str) -> Response: - """Opens up the browser and do your request based on your chosen options. - - :param url: Target url. - :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` - """ - - sync_context = sync_rebrowser_playwright - if not self.stealth or self.real_chrome: - # Because rebrowser_playwright doesn't play well with real browsers - sync_context = sync_playwright - - final_response = None - referer = generate_convincing_referer(url) if self.google_search else None - - def handle_response(finished_response: SyncPlaywrightResponse): - nonlocal final_response - if ( - finished_response.request.resource_type == "document" - and finished_response.request.is_navigation_request() - ): - final_response = finished_response - - with sync_context() as p: - # Creating the browser - if self.cdp_url: - cdp_url = self._cdp_url_logic() - browser = p.chromium.connect_over_cdp(endpoint_url=cdp_url) - else: - browser = p.chromium.launch(**self.__launch_kwargs()) - - context = browser.new_context(**self.__context_kwargs()) - if self.cookies: - context.add_cookies(self.cookies) - - page = context.new_page() - page.set_default_navigation_timeout(self.timeout) - page.set_default_timeout(self.timeout) - page.on("response", handle_response) - - if self.extra_headers: - page.set_extra_http_headers(self.extra_headers) - - if self.disable_resources: - page.route("**/*", intercept_route) - - if self.stealth: - for script in self.__stealth_scripts(): - page.add_init_script(path=script) - - first_response = page.goto(url, referer=referer) - page.wait_for_load_state(state="domcontentloaded") - - if self.network_idle: - page.wait_for_load_state("networkidle") - - if self.page_action is not None: - try: - page = self.page_action(page) - except Exception as e: - log.error(f"Error executing page_action: {e}") - - if self.wait_selector and type(self.wait_selector) is str: - try: - waiter = page.locator(self.wait_selector) - waiter.first.wait_for(state=self.wait_selector_state) - # Wait again after waiting for the selector, helpful with protections like Cloudflare - page.wait_for_load_state(state="load") - page.wait_for_load_state(state="domcontentloaded") - if self.network_idle: - page.wait_for_load_state("networkidle") - except Exception as e: - log.error(f"Error waiting for selector {self.wait_selector}: {e}") - - page.wait_for_timeout(self.wait) - response = ResponseFactory.from_playwright_response( - page, first_response, final_response, self.adaptor_arguments - ) - page.close() - context.close() - return response - - async def async_fetch(self, url: str) -> Response: - """Async version of `fetch` - - :param url: Target url. - :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` - """ - - async_context = async_rebrowser_playwright - if not self.stealth or self.real_chrome: - # Because rebrowser_playwright doesn't play well with real browsers - async_context = async_playwright - - final_response = None - referer = generate_convincing_referer(url) if self.google_search else None - - async def handle_response(finished_response: AsyncPlaywrightResponse): - nonlocal final_response - if ( - finished_response.request.resource_type == "document" - and finished_response.request.is_navigation_request() - ): - final_response = finished_response - - async with async_context() as p: - # Creating the browser - if self.cdp_url: - cdp_url = self._cdp_url_logic() - browser = await p.chromium.connect_over_cdp(endpoint_url=cdp_url) - else: - browser = await p.chromium.launch(**self.__launch_kwargs()) - - context = await browser.new_context(**self.__context_kwargs()) - if self.cookies: - await context.add_cookies(self.cookies) - - page = await context.new_page() - page.set_default_navigation_timeout(self.timeout) - page.set_default_timeout(self.timeout) - page.on("response", handle_response) - - if self.extra_headers: - await page.set_extra_http_headers(self.extra_headers) - - if self.disable_resources: - await page.route("**/*", async_intercept_route) - - if self.stealth: - for script in self.__stealth_scripts(): - await page.add_init_script(path=script) - - first_response = await page.goto(url, referer=referer) - await page.wait_for_load_state(state="domcontentloaded") - - if self.network_idle: - await page.wait_for_load_state("networkidle") - - if self.page_action is not None: - try: - page = await self.page_action(page) - except Exception as e: - log.error(f"Error executing async page_action: {e}") - - if self.wait_selector and type(self.wait_selector) is str: - try: - waiter = page.locator(self.wait_selector) - await waiter.first.wait_for(state=self.wait_selector_state) - # Wait again after waiting for the selector, helpful with protections like Cloudflare - await page.wait_for_load_state(state="load") - await page.wait_for_load_state(state="domcontentloaded") - if self.network_idle: - await page.wait_for_load_state("networkidle") - except Exception as e: - log.error(f"Error waiting for selector {self.wait_selector}: {e}") - - await page.wait_for_timeout(self.wait) - response = await ResponseFactory.from_async_playwright_response( - page, first_response, final_response, self.adaptor_arguments - ) - await page.close() - await context.close() - - return response diff --git a/scrapling/fetchers.py b/scrapling/fetchers.py index 9954b35..ef66341 100644 --- a/scrapling/fetchers.py +++ b/scrapling/fetchers.py @@ -11,7 +11,8 @@ from scrapling.core._types import ( from scrapling.engines import ( FetcherSession, CamoufoxEngine, - PlaywrightEngine, + DynamicSession, + AsyncDynamicSession, check_if_engine_usable, FetcherClient as _FetcherClient, AsyncFetcherClient as _AsyncFetcherClient, @@ -237,7 +238,7 @@ class StealthyFetcher(BaseFetcher): return await engine.async_fetch(url) -class PlayWrightFetcher(BaseFetcher): +class DynamicFetcher(BaseFetcher): """A `Fetcher` class type that provide many options, all of them are based on PlayWright. Using this Fetcher class, you can do requests with: @@ -258,28 +259,27 @@ class PlayWrightFetcher(BaseFetcher): def fetch( cls, url: str, - headless: Union[bool, str] = True, - disable_resources: bool = None, - useragent: Optional[str] = None, - network_idle: bool = False, - timeout: Optional[float] = 30000, - wait: Optional[int] = 0, - cookies: Optional[Iterable[Dict]] = None, - page_action: Optional[Callable] = None, - wait_selector: Optional[str] = None, - wait_selector_state: SelectorWaitStates = "attached", + max_pages: int = 1, + headless: bool = True, + google_search: bool = True, hide_canvas: bool = False, disable_webgl: bool = False, - extra_headers: Optional[Dict[str, str]] = None, - google_search: bool = True, - proxy: Optional[Union[str, Dict[str, str]]] = None, - locale: Optional[str] = "en-US", - stealth: bool = False, real_chrome: bool = False, + stealth: bool = False, + wait: Union[int, float] = 0, + page_action: Optional[Callable] = None, + proxy: Optional[Union[str, Dict[str, str]]] = None, + locale: str = "en-US", + extra_headers: Optional[Dict[str, str]] = None, + useragent: Optional[str] = None, cdp_url: Optional[str] = None, - nstbrowser_mode: bool = False, - nstbrowser_config: Optional[Dict] = None, - custom_config: Dict = None, + timeout: Union[int, float] = 30000, + disable_resources: bool = False, + wait_selector: Optional[str] = None, + cookies: Optional[Iterable[Dict]] = None, + network_idle: bool = False, + wait_selector_state: SelectorWaitStates = "attached", + custom_config: Optional[Dict] = None, ) -> Response: """Opens up a browser and do your request based on your chosen options below. @@ -289,10 +289,10 @@ class PlayWrightFetcher(BaseFetcher): Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`. This can help save your proxy usage but be careful with this option as it makes some websites never finish loading. :param useragent: Pass a useragent string to be used. Otherwise the fetcher will generate a real Useragent of the same browser and use it. + :param cookies: Set cookies for the next request. :param network_idle: Wait for the page until there are no network connections for at least 500 ms. :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000 :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the ` Response ` object. - :param cookies: Set cookies for the next request. :param page_action: Added for automation. A function that takes the `page` object, does the automation you need, then returns `page` again. :param wait_selector: Wait for a specific CSS selector to be in a specific state. :param locale: Set the locale for the browser if wanted. The default value is `en-US`. @@ -302,22 +302,21 @@ class PlayWrightFetcher(BaseFetcher): :param hide_canvas: Add random noise to canvas operations to prevent fingerprinting. :param disable_webgl: Disables WebGL and WebGL 2.0 support entirely. :param cdp_url: Instead of launching a new browser instance, connect to this CDP URL to control real browsers/NSTBrowser through CDP. - :param nstbrowser_mode: Enables NSTBrowser mode, it has to be used with the ` cdp_url ` argument, or it will get completely ignored. :param google_search: Enabled by default, Scrapling will set the referer header to be as if this request came from a Google search for this website's domain name. :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by the `google_search` argument takes priority over the referer set here if used together._ :param proxy: The proxy to be used with requests, it can be a string or a dictionary with the keys 'server', 'username', and 'password' only. - :param nstbrowser_config: The config you want to send with requests to the NSTBrowser. If left empty, Scrapling defaults to an optimized NSTBrowser's docker browserless config. + :param max_pages: The maximum number of tabs to be opened at the same time. It will be used in rotation through a PagePool. :param custom_config: A dictionary of custom parser arguments to use with this request. Any argument passed will override any class parameters values. - :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` + :return: A `Response` object. """ if not custom_config: custom_config = {} elif not isinstance(custom_config, dict): - ValueError( + raise ValueError( f"The custom parser config must be of type dictionary, got {cls.__class__}" ) - engine = PlaywrightEngine( + with DynamicSession( wait=wait, proxy=proxy, locale=locale, @@ -327,6 +326,7 @@ class PlayWrightFetcher(BaseFetcher): cookies=cookies, headless=headless, useragent=useragent, + max_pages=max_pages, real_chrome=real_chrome, page_action=page_action, hide_canvas=hide_canvas, @@ -335,40 +335,39 @@ class PlayWrightFetcher(BaseFetcher): extra_headers=extra_headers, wait_selector=wait_selector, disable_webgl=disable_webgl, - nstbrowser_mode=nstbrowser_mode, - nstbrowser_config=nstbrowser_config, disable_resources=disable_resources, wait_selector_state=wait_selector_state, adaptor_arguments={**cls._generate_parser_arguments(), **custom_config}, - ) - return engine.fetch(url) + ) as session: + response = session.fetch(url) + + return response @classmethod async def async_fetch( cls, url: str, - headless: Union[bool, str] = True, - disable_resources: bool = None, - useragent: Optional[str] = None, - network_idle: bool = False, - timeout: Optional[float] = 30000, - wait: Optional[int] = 0, - cookies: Optional[Iterable[Dict]] = None, - page_action: Optional[Callable] = None, - wait_selector: Optional[str] = None, - wait_selector_state: SelectorWaitStates = "attached", + max_pages: int = 1, + headless: bool = True, + google_search: bool = True, hide_canvas: bool = False, disable_webgl: bool = False, - extra_headers: Optional[Dict[str, str]] = None, - google_search: bool = True, - proxy: Optional[Union[str, Dict[str, str]]] = None, - locale: Optional[str] = "en-US", - stealth: bool = False, real_chrome: bool = False, + stealth: bool = False, + wait: Union[int, float] = 0, + page_action: Optional[Callable] = None, + proxy: Optional[Union[str, Dict[str, str]]] = None, + locale: str = "en-US", + extra_headers: Optional[Dict[str, str]] = None, + useragent: Optional[str] = None, cdp_url: Optional[str] = None, - nstbrowser_mode: bool = False, - nstbrowser_config: Optional[Dict] = None, - custom_config: Dict = None, + timeout: Union[int, float] = 30000, + disable_resources: bool = False, + wait_selector: Optional[str] = None, + cookies: Optional[Iterable[Dict]] = None, + network_idle: bool = False, + wait_selector_state: SelectorWaitStates = "attached", + custom_config: Optional[Dict] = None, ) -> Response: """Opens up a browser and do your request based on your chosen options below. @@ -378,8 +377,8 @@ class PlayWrightFetcher(BaseFetcher): Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`. This can help save your proxy usage but be careful with this option as it makes some websites never finish loading. :param useragent: Pass a useragent string to be used. Otherwise the fetcher will generate a real Useragent of the same browser and use it. - :param network_idle: Wait for the page until there are no network connections for at least 500 ms. :param cookies: Set cookies for the next request. + :param network_idle: Wait for the page until there are no network connections for at least 500 ms. :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000 :param wait: The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the ` Response ` object. :param page_action: Added for automation. A function that takes the `page` object, does the automation you need, then returns `page` again. @@ -391,22 +390,21 @@ class PlayWrightFetcher(BaseFetcher): :param hide_canvas: Add random noise to canvas operations to prevent fingerprinting. :param disable_webgl: Disables WebGL and WebGL 2.0 support entirely. :param cdp_url: Instead of launching a new browser instance, connect to this CDP URL to control real browsers/NSTBrowser through CDP. - :param nstbrowser_mode: Enables NSTBrowser mode, it has to be used with the ` cdp_url ` argument, or it will get completely ignored. :param google_search: Enabled by default, Scrapling will set the referer header to be as if this request came from a Google search for this website's domain name. :param extra_headers: A dictionary of extra headers to add to the request. _The referer set by the `google_search` argument takes priority over the referer set here if used together._ :param proxy: The proxy to be used with requests, it can be a string or a dictionary with the keys 'server', 'username', and 'password' only. - :param nstbrowser_config: The config you want to send with requests to the NSTBrowser. If left empty, Scrapling defaults to an optimized NSTBrowser's docker browserless config. + :param max_pages: The maximum number of tabs to be opened at the same time. It will be used in rotation through a PagePool. :param custom_config: A dictionary of custom parser arguments to use with this request. Any argument passed will override any class parameters values. - :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` + :return: A `Response` object. """ if not custom_config: custom_config = {} elif not isinstance(custom_config, dict): - ValueError( + raise ValueError( f"The custom parser config must be of type dictionary, got {cls.__class__}" ) - engine = PlaywrightEngine( + async with AsyncDynamicSession( wait=wait, proxy=proxy, locale=locale, @@ -416,6 +414,7 @@ class PlayWrightFetcher(BaseFetcher): cookies=cookies, headless=headless, useragent=useragent, + max_pages=max_pages, real_chrome=real_chrome, page_action=page_action, hide_canvas=hide_canvas, @@ -424,13 +423,16 @@ class PlayWrightFetcher(BaseFetcher): extra_headers=extra_headers, wait_selector=wait_selector, disable_webgl=disable_webgl, - nstbrowser_mode=nstbrowser_mode, - nstbrowser_config=nstbrowser_config, disable_resources=disable_resources, wait_selector_state=wait_selector_state, adaptor_arguments={**cls._generate_parser_arguments(), **custom_config}, - ) - return await engine.async_fetch(url) + ) as session: + response = await session.fetch(url) + + return response + + +PlayWrightFetcher = DynamicFetcher # For backward-compatibility class CustomFetcher(BaseFetcher):