From ab7b0d45ad4545e4fac1f3eb028220f51d455276 Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Wed, 13 Nov 2024 23:13:39 +0200 Subject: [PATCH 01/13] StaticEngine - Fix the headers bug --- scrapling/engines/static.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scrapling/engines/static.py b/scrapling/engines/static.py index 217cd50..ffc8822 100644 --- a/scrapling/engines/static.py +++ b/scrapling/engines/static.py @@ -71,7 +71,7 @@ class StaticEngine: :param kwargs: Any additional keyword arguments are passed directly to `httpx.get()` function so check httpx documentation for details. :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. """ - headers = self._headers_job(kwargs.get('headers'), url, stealthy_headers) + headers = self._headers_job(kwargs.pop('headers', {}), url, stealthy_headers) request = httpx.get(url=url, headers=headers, follow_redirects=self.follow_redirects, timeout=self.timeout, **kwargs) return self._prepare_response(request) @@ -83,7 +83,7 @@ class StaticEngine: :param kwargs: Any additional keyword arguments are passed directly to `httpx.post()` function so check httpx documentation for details. :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. """ - headers = self._headers_job(kwargs.get('headers'), url, stealthy_headers) + headers = self._headers_job(kwargs.pop('headers', {}), url, stealthy_headers) request = httpx.post(url=url, headers=headers, follow_redirects=self.follow_redirects, timeout=self.timeout, **kwargs) return self._prepare_response(request) @@ -95,7 +95,7 @@ class StaticEngine: :param kwargs: Any additional keyword arguments are passed directly to `httpx.delete()` function so check httpx documentation for details. :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. """ - headers = self._headers_job(kwargs.get('headers'), url, stealthy_headers) + headers = self._headers_job(kwargs.pop('headers', {}), url, stealthy_headers) request = httpx.delete(url=url, headers=headers, follow_redirects=self.follow_redirects, timeout=self.timeout, **kwargs) return self._prepare_response(request) @@ -107,6 +107,6 @@ class StaticEngine: :param kwargs: Any additional keyword arguments are passed directly to `httpx.put()` function so check httpx documentation for details. :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. """ - headers = self._headers_job(kwargs.get('headers'), url, stealthy_headers) + headers = self._headers_job(kwargs.pop('headers', {}), url, stealthy_headers) request = httpx.put(url=url, headers=headers, follow_redirects=self.follow_redirects, timeout=self.timeout, **kwargs) return self._prepare_response(request) From d4b896b4e964b7db704f31249d308b5934af3bfd Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Wed, 13 Nov 2024 23:14:27 +0200 Subject: [PATCH 02/13] Parser - New logic to handle JSON responses passed from Fetchers --- scrapling/parser.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/scrapling/parser.py b/scrapling/parser.py index cac7fef..a9945d0 100644 --- a/scrapling/parser.py +++ b/scrapling/parser.py @@ -10,6 +10,7 @@ from scrapling.core.storage_adaptors import SQLiteStorageSystem, StorageSystemMi from scrapling.core.utils import setup_basic_logging, logging, clean_spaces, flatten, html_forbidden from scrapling.core._types import Any, Dict, List, Tuple, Optional, Pattern, Union, Callable, Generator, SupportsIndex, Iterable from lxml import etree, html +from lxml.etree import XMLSyntaxError from cssselect import SelectorError, SelectorSyntaxError, parse as split_selectors @@ -60,6 +61,7 @@ class Adaptor(SelectorsGeneration): if root is None and not body and text is None: raise ValueError("Adaptor class needs text, body, or root arguments to work") + self.__text = None if root is None: if text is None: if not body or not isinstance(body, bytes): @@ -72,12 +74,21 @@ class Adaptor(SelectorsGeneration): body = text.strip().replace("\x00", "").encode(encoding) or b"" - parser = html.HTMLParser( - # https://lxml.de/api/lxml.etree.HTMLParser-class.html - recover=True, remove_blank_text=True, remove_comments=(keep_comments is False), encoding=encoding, - compact=True, huge_tree=huge_tree, default_doctype=True - ) - self._root = etree.fromstring(body, parser=parser, base_url=url) + # https://lxml.de/api/lxml.etree.HTMLParser-class.html + try: + # Test with recover set to False first so if this is a text body like a json response, we get error + parser = html.HTMLParser( + recover=False, remove_blank_text=True, remove_comments=(keep_comments is False), encoding=encoding, + compact=True, huge_tree=huge_tree, default_doctype=True + ) + self._root = etree.fromstring(body, parser=parser, base_url=url) + except XMLSyntaxError: + parser = html.HTMLParser( + recover=True, remove_blank_text=True, remove_comments=(keep_comments is False), encoding=encoding, + compact=True, huge_tree=huge_tree, default_doctype=True + ) + self._root = etree.fromstring(body, parser=parser, base_url=url) + self.__text = TextHandler(text or body.decode()) else: # All html types inherits from HtmlMixin so this to check for all at once @@ -112,7 +123,6 @@ class Adaptor(SelectorsGeneration): self.url = url # For selector stuff self.__attributes = None - self.__text = None self.__tag = None self.__debug = debug From eaa7da27c6f254e664729c2c7c402aadf4e356e1 Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Thu, 14 Nov 2024 00:03:26 +0200 Subject: [PATCH 03/13] Better logic to handle json responses --- scrapling/core/utils.py | 14 +++++++++++++- scrapling/parser.py | 22 +++++++--------------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/scrapling/core/utils.py b/scrapling/core/utils.py index db5ef15..748020b 100644 --- a/scrapling/core/utils.py +++ b/scrapling/core/utils.py @@ -4,8 +4,9 @@ from itertools import chain # Using cache on top of a class is brilliant way to achieve Singleton design pattern without much code from functools import lru_cache as cache # functools.cache is available on Python 3.9+ only so let's keep lru_cache -from scrapling.core._types import Dict, Iterable, Any +from scrapling.core._types import Dict, Iterable, Any, Union +import orjson from lxml import html html_forbidden = {html.HtmlComment, } @@ -18,6 +19,17 @@ logging.basicConfig( ) +def is_jsonable(content: Union[bytes, str]) -> bool: + if type(content) is bytes: + content = content.decode() + + try: + _ = orjson.loads(content) + return True + except orjson.JSONDecodeError: + return False + + @cache(None, typed=True) def setup_basic_logging(level: str = 'debug'): levels = { diff --git a/scrapling/parser.py b/scrapling/parser.py index a9945d0..e74e5cb 100644 --- a/scrapling/parser.py +++ b/scrapling/parser.py @@ -7,10 +7,9 @@ from scrapling.core.translator import HTMLTranslator from scrapling.core.mixins import SelectorsGeneration from scrapling.core.custom_types import TextHandler, TextHandlers, AttributesHandler from scrapling.core.storage_adaptors import SQLiteStorageSystem, StorageSystemMixin, _StorageTools -from scrapling.core.utils import setup_basic_logging, logging, clean_spaces, flatten, html_forbidden +from scrapling.core.utils import setup_basic_logging, logging, clean_spaces, flatten, html_forbidden, is_jsonable from scrapling.core._types import Any, Dict, List, Tuple, Optional, Pattern, Union, Callable, Generator, SupportsIndex, Iterable from lxml import etree, html -from lxml.etree import XMLSyntaxError from cssselect import SelectorError, SelectorSyntaxError, parse as split_selectors @@ -75,19 +74,12 @@ class Adaptor(SelectorsGeneration): body = text.strip().replace("\x00", "").encode(encoding) or b"" # https://lxml.de/api/lxml.etree.HTMLParser-class.html - try: - # Test with recover set to False first so if this is a text body like a json response, we get error - parser = html.HTMLParser( - recover=False, remove_blank_text=True, remove_comments=(keep_comments is False), encoding=encoding, - compact=True, huge_tree=huge_tree, default_doctype=True - ) - self._root = etree.fromstring(body, parser=parser, base_url=url) - except XMLSyntaxError: - parser = html.HTMLParser( - recover=True, remove_blank_text=True, remove_comments=(keep_comments is False), encoding=encoding, - compact=True, huge_tree=huge_tree, default_doctype=True - ) - self._root = etree.fromstring(body, parser=parser, base_url=url) + parser = html.HTMLParser( + recover=True, remove_blank_text=True, remove_comments=(keep_comments is False), encoding=encoding, + compact=True, huge_tree=huge_tree, default_doctype=True + ) + self._root = etree.fromstring(body, parser=parser, base_url=url) + if is_jsonable(text or body.decode()): self.__text = TextHandler(text or body.decode()) else: From ea81e0284d5a95ffe891a12382290107837650f1 Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Thu, 14 Nov 2024 16:33:28 +0200 Subject: [PATCH 04/13] Update tests Github action --- .github/workflows/tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 1e61a4f..a56cd39 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,5 +1,5 @@ name: Tests -on: [push, pull_request] +on: [push] concurrency: group: ${{github.workflow}}-${{ github.ref }} From b0c2b1818b9abcc31eec86c630de6be1e4e428fa Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Thu, 14 Nov 2024 22:21:45 +0200 Subject: [PATCH 05/13] Return to the default text behaviour The logic to remove comment tags before returning text was causing errors sometimes so from now on leave `keep_comments` set to True better as it is. --- scrapling/parser.py | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/scrapling/parser.py b/scrapling/parser.py index e74e5cb..8d03dda 100644 --- a/scrapling/parser.py +++ b/scrapling/parser.py @@ -187,23 +187,9 @@ class Adaptor(SelectorsGeneration): def text(self) -> TextHandler: """Get text content of the element""" if not self.__text: - if self.__keep_comments: - if not self.children: - # If use chose to keep comments, remove comments from text - # Escape lxml default behaviour and remove comments like this `CONDITION: Excellent` - # This issue is present in parsel/scrapy as well so no need to repeat it here so the user can run regex on the full text. - code = self.html_content - parser = html.HTMLParser( - recover=True, remove_blank_text=True, remove_comments=True, encoding=self.encoding, - compact=True, huge_tree=self.__huge_tree_enabled, default_doctype=True - ) - fragment_root = html.fragment_fromstring(code, parser=parser) - self.__text = TextHandler(fragment_root.text) - else: - self.__text = TextHandler(self._root.text) - else: - # If user already chose to not keep comments then all is good - self.__text = TextHandler(self._root.text) + # If you want to escape lxml default behaviour and remove comments like this `CONDITION: Excellent` + # before extracting text then keep `keep_comments` set to False while initializing the first class + self.__text = TextHandler(self._root.text) return self.__text def get_all_text(self, separator: str = "\n", strip: bool = False, ignore_tags: Tuple = ('script', 'style',), valid_values: bool = True) -> TextHandler: From 095d50cd7585a1f04f8d674afbb079a053aa7743 Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Fri, 15 Nov 2024 02:23:14 +0200 Subject: [PATCH 06/13] Making the Response returned from all fetchers same as `Adaptor` object but with added attributes --- scrapling/engines/toolbelt/custom.py | 42 ++++++++++------------------ 1 file changed, 14 insertions(+), 28 deletions(-) diff --git a/scrapling/engines/toolbelt/custom.py b/scrapling/engines/toolbelt/custom.py index 3688be2..274654c 100644 --- a/scrapling/engines/toolbelt/custom.py +++ b/scrapling/engines/toolbelt/custom.py @@ -3,43 +3,29 @@ Functions related to custom types or type checking """ import inspect import logging -from dataclasses import dataclass, field from scrapling.core.utils import setup_basic_logging from scrapling.parser import Adaptor, SQLiteStorageSystem from scrapling.core._types import Any, List, Type, Union, Optional, Dict, Callable -@dataclass(frozen=True) -class Response: +class Response(Adaptor): """This class is returned by all engines as a way to unify response type between different libraries.""" - url: str - text: str - content: bytes - status: int - reason: str - encoding: str = 'utf-8' # default encoding - cookies: Dict = field(default_factory=dict) - headers: Dict = field(default_factory=dict) - request_headers: Dict = field(default_factory=dict) - adaptor_arguments: Dict = field(default_factory=dict) - @property - def adaptor(self) -> Union[Adaptor, None]: - """Generate Adaptor instance from this response if possible, otherwise return None""" - automatch_domain = self.adaptor_arguments.pop('automatch_domain', None) - if self.text: - # For playwright that will be the response after all JS executed - return Adaptor(text=self.text, url=automatch_domain or self.url, encoding=self.encoding, **self.adaptor_arguments) - elif self.content: - # For playwright, that's after all JS is loaded but not all of them executed, because playwright doesn't offer something like page.content() - # To get response Bytes after the load states - # Reference: https://playwright.dev/python/docs/api/class-page - return Adaptor(body=self.content, url=automatch_domain or self.url, encoding=self.encoding, **self.adaptor_arguments) - return None + def __init__(self, url: str, text: str, content: bytes, status: int, reason: str, cookies: Dict, headers: Dict, request_headers: Dict, adaptor_arguments: Dict, encoding: str = 'utf-8'): + automatch_domain = adaptor_arguments.pop('automatch_domain', None) + super().__init__(text=text, body=content, url=automatch_domain or url, encoding=encoding, **adaptor_arguments) - def __repr__(self): - return f'<{self.__class__.__name__} [{self.status} {self.reason}]>' + self.status = status + self.reason = reason + self.cookies = cookies + self.headers = headers + self.request_headers = request_headers + # For back-ward compatibility + self.adaptor = self + + # def __repr__(self): + # return f'<{self.__class__.__name__} [{self.status} {self.reason}]>' class BaseFetcher: From c33475537766c3c62cc44996933ae35c7630d8a7 Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Fri, 15 Nov 2024 02:33:47 +0200 Subject: [PATCH 07/13] Reflecting the new changes in the README and adding small notes --- README.md | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 0d50104..159027f 100644 --- a/README.md +++ b/README.md @@ -8,10 +8,9 @@ Scrapling is a high-performance, intelligent web scraping library for Python tha ```python >> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher # Fetch websites' source under the radar! ->> fetcher = StealthyFetcher().fetch('https://example.com', headless=True, disable_resources=True) ->> print(fetcher.status) +>> page = StealthyFetcher().fetch('https://example.com', headless=True, disable_resources=True) +>> print(page.status) 200 ->> page = fetcher.adaptor >> products = page.css('.product', auto_save=True) # Scrape data that survives website design changes! >> # Later, if the website structure changes, pass `auto_match=True` >> products = page.css('.product', auto_match=True) # and Scrapling still finds them! @@ -107,7 +106,7 @@ from scrapling import Fetcher fetcher = Fetcher(auto_match=False) # Fetch a web page and create an Adaptor instance -page = fetcher.get('https://quotes.toscrape.com/', stealthy_headers=True).adaptor +page = fetcher.get('https://quotes.toscrape.com/', stealthy_headers=True) # Get all strings in the full page page.get_all_text(ignore_tags=('script', 'style')) @@ -217,6 +216,8 @@ All fetcher-type classes are imported in the same way from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher ``` And all of them can take these initialization arguments: `auto_match`, `huge_tree`, `keep_comments`, `storage`, `storage_args`, and `debug` which are the same ones you give to the `Adaptor` class. + +Also, the `Response` object returned from all fetchers is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers`. All `cookies`, `headers`, and `request_headers` are always of type `dictionary`. > [!NOTE] > The `auto_match` argument is enabled by default which is the one you should care about the most as you will see later. ### Fetcher @@ -236,6 +237,8 @@ This class is built on top of [Camoufox](https://github.com/daijro/camoufox) whi >> page.status == 200 True ``` +> Note: all requests done by this fetcher is waiting by default for all JS to be fully loaded and executed so you don't have to :) +
For the sake of simplicity, expand this for the complete list of arguments | Argument | Description | Optional | @@ -264,9 +267,11 @@ This list isn't final so expect a lot more additions and flexibility to be added This class is built on top of [Playwright](https://playwright.dev/python/) which currently provides 4 main run options but they can be mixed as you want. ```python >> page = PlayWrightFetcher().fetch('https://www.google.com/search?q=%22Scrapling%22', disable_resources=True) # Vanilla Playwright option ->> page.adaptor.css_first("#search a::attr(href)") +>> page.css_first("#search a::attr(href)") 'https://github.com/D4Vinci/Scrapling' ``` +> Note: all requests done by this fetcher is waiting by default for all JS to be fully loaded and executed so you don't have to :) + Using this Fetcher class, you can make requests with: 1) Vanilla Playwright without any modifications other than the ones you chose. 2) Stealthy Playwright with the stealth mode I wrote for it. It's still a WIP but it bypasses many online tests like [Sannysoft's](https://bot.sannysoft.com/).
Some of the things this fetcher's stealth mode does include: @@ -358,7 +363,7 @@ You can search for a specific ancestor of an element that satisfies a function, ### Content-based Selection & Finding Similar Elements You can select elements by their text content in multiple ways, here's a full example on another website: ```python ->>> page = Fetcher().get('https://books.toscrape.com/index.html').adaptor +>>> page = Fetcher().get('https://books.toscrape.com/index.html') >>> page.find_by_text('Tipping the Velvet') # Find the first element whose text fully matches this text @@ -478,11 +483,11 @@ Now let's test the same selector in both versions >> old_url = "https://web.archive.org/web/20100102003420/http://stackoverflow.com/" >> new_url = "https://stackoverflow.com/" >> ->> page = Fetcher(automatch_domain='stackoverflow.com').get(old_url, timeout=30).adaptor +>> page = Fetcher(automatch_domain='stackoverflow.com').get(old_url, timeout=30) >> element1 = page.css_first(selector, auto_save=True) >> >> # Same selector but used in the updated website ->> page = Fetcher(automatch_domain="stackoverflow.com").get(new_url).adaptor +>> page = Fetcher(automatch_domain="stackoverflow.com").get(new_url) >> element2 = page.css_first(selector, auto_match=True) >> >> if element1.text == element2.text: @@ -494,7 +499,7 @@ Note that I used a new argument called `automatch_domain`, this is because for S In a real-world scenario, the code will be the same except it will use the same URL for both requests so you won't need to use the `automatch_domain` argument. This is the closest example I can give to real-world cases so I hope it didn't confuse you :) **Notes:** -1. For the two examples above I used one time the `Adaptor` class and the second time the `Fetcher` class just to show you that you can create the `Adaptor` object by yourself if you have the source or fetch the source using any `Fetcher` class then it will create the `Adaptor` object for you on the `.adaptor` property. +1. For the two examples above I used one time the `Adaptor` class and the second time the `Fetcher` class just to show you that you can create the `Adaptor` object by yourself if you have the source or fetch the source using any `Fetcher` class then it will create the `Adaptor` object for you. 2. Passing the `auto_save` argument with the `auto_match` argument set to `False` while initializing the Adaptor/Fetcher object will only result in ignoring the `auto_save` argument value and the following warning message ```text Argument `auto_save` will be ignored because `auto_match` wasn't enabled on initialization. Check docs for more info. @@ -535,7 +540,7 @@ Examples to clear any confusion :) ```python >> from scrapling import Fetcher ->> page = Fetcher().get('https://quotes.toscrape.com/').adaptor +>> page = Fetcher().get('https://quotes.toscrape.com/') # Find all elements with tag name `div`. >> page.find_all('div') [
, From 7dd9d3090d9b34ea73ca369e8d9570c1f333d9a3 Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Fri, 15 Nov 2024 02:43:29 +0200 Subject: [PATCH 08/13] Pumping the version up to 0.2.1 --- scrapling/__init__.py | 2 +- setup.cfg | 4 ++-- setup.py | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/scrapling/__init__.py b/scrapling/__init__.py index d33f63a..4b3b69b 100644 --- a/scrapling/__init__.py +++ b/scrapling/__init__.py @@ -4,7 +4,7 @@ from scrapling.parser import Adaptor, Adaptors from scrapling.core.custom_types import TextHandler, AttributesHandler __author__ = "Karim Shoair (karim.shoair@pm.me)" -__version__ = "0.2" +__version__ = "0.2.1" __copyright__ = "Copyright (c) 2024 Karim Shoair" diff --git a/setup.cfg b/setup.cfg index 3c6197a..69c8d16 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,8 +1,8 @@ [metadata] name = scrapling -version = 0.2 +version = 0.2.1 author = Karim Shoair author_email = karim.shoair@pm.me -description = Scrapling is a powerful, flexible, adaptive, and high-performance web scraping library for Python. +description = Scrapling is an undetectable, powerful, flexible, adaptive, and high-performance web scraping library for Python. license = BSD home_page = https://github.com/D4Vinci/Scrapling \ No newline at end of file diff --git a/setup.py b/setup.py index 5cb769d..63340b9 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,7 @@ with open("README.md", "r", encoding="utf-8") as fh: setup( name="scrapling", - version="0.2", + version="0.2.1", description="""Scrapling is a powerful, flexible, and high-performance web scraping library for Python. It simplifies the process of extracting data from websites, even when they undergo structural changes, and offers impressive speed improvements over many popular scraping tools.""", @@ -57,7 +57,7 @@ setup( 'httpx[brotli,zstd]', 'playwright', 'rebrowser-playwright', - 'camoufox>=0.3.7', + 'camoufox>=0.3.9', 'browserforge', ], python_requires=">=3.8", From ae7959b4a471e884918c6381df2c6dac5f20787b Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Fri, 15 Nov 2024 02:50:24 +0200 Subject: [PATCH 09/13] Update README.md --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 159027f..891f7b5 100644 --- a/README.md +++ b/README.md @@ -703,7 +703,10 @@ There are a lot of deep details skipped here to make this as short as possible s Note that implementing your storage system can be complex as there are some strict rules such as inheriting from the same abstract class, following the singleton design pattern used in other classes, and more. So make sure to read the docs first. -To give detailed documentation of the library, it will need a website. I'm trying to rush creating the website, researching new ideas, and adding more features/tests/benchmarks but time is tight with too many spinning plates between work, personal life, and working on Scrapling. But you can help by using the [sponsor button](https://github.com/sponsors/D4Vinci) above :) +> [!IMPORTANT] +> To give detailed documentation of the library, it will need a website. +> I'm trying to rush creating the website, researching new ideas, and adding more features/tests/benchmarks but time is tight with too many spinning plates between work, personal life, and working on Scrapling. +> If you like `Scrapling` and want it to keep improving then this is a friendly reminder that you can help by supporting me through the [sponsor button](https://github.com/sponsors/D4Vinci). ## ⚡ Enlightening Questions and FAQs This section addresses common questions about Scrapling, please read this section before opening an issue. From b993adb4a7c34eeda93a89698266b74e3e11c36e Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Fri, 15 Nov 2024 11:26:41 +0200 Subject: [PATCH 10/13] Rephrasing some parts --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 891f7b5..33ebbf9 100644 --- a/README.md +++ b/README.md @@ -704,8 +704,8 @@ There are a lot of deep details skipped here to make this as short as possible s Note that implementing your storage system can be complex as there are some strict rules such as inheriting from the same abstract class, following the singleton design pattern used in other classes, and more. So make sure to read the docs first. > [!IMPORTANT] -> To give detailed documentation of the library, it will need a website. -> I'm trying to rush creating the website, researching new ideas, and adding more features/tests/benchmarks but time is tight with too many spinning plates between work, personal life, and working on Scrapling. +> A website is needed to provide detailed library documentation.
+> I'm trying to rush creating the website, researching new ideas, and adding more features/tests/benchmarks but time is tight with too many spinning plates between work, personal life, and working on Scrapling. I have been working on Scrapling for months for free after all.

> If you like `Scrapling` and want it to keep improving then this is a friendly reminder that you can help by supporting me through the [sponsor button](https://github.com/sponsors/D4Vinci). ## ⚡ Enlightening Questions and FAQs @@ -720,8 +720,8 @@ This section addresses common questions about Scrapling, please read this sectio Together both are used to retrieve the element's unique properties from the database later. 4. Now later when you enable the `auto_match` parameter for both the Adaptor instance and the method call. The element properties are retrieved and Scrapling loops over all elements in the page and compares each one's unique properties to the unique properties we already have for this element and a score is calculated for each one. - 5. The comparison between elements is not exact but more about finding how similar these values are, so everything is taken into consideration even the values' order like the order in which the element class names were written before and the order in which the same element class names are written now. - 6. The score for each element is stored in the table, and in the end, the element(s) with the highest combined similarity scores are returned. + 5. Comparing elements is not exact but more about finding how similar these values are, so everything is taken into consideration, even the values' order, like the order in which the element class names were written before and the order in which the same element class names are written now. + 6. The score for each element is stored in the table, and the element(s) with the highest combined similarity scores are returned. ### How does the auto-matching work if I didn't pass a URL while initializing the Adaptor object? Not a big problem as it depends on your usage. The word `default` will be used in place of the URL field while saving the element's unique properties. So this will only be an issue if you used the same identifier later for a different website that you didn't pass the URL parameter while initializing it as well. The save process will overwrite the previous data and auto-matching uses the latest saved properties only. From 2abb70218f46e9889cafb13cf6d0150aa8711793 Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Fri, 15 Nov 2024 14:43:03 +0200 Subject: [PATCH 11/13] Adding the proxy support to browser-based Fetchers --- README.md | 2 ++ scrapling/engines/camo.py | 7 ++++- scrapling/engines/pw.py | 7 ++++- scrapling/engines/toolbelt/__init__.py | 1 + scrapling/engines/toolbelt/navigation.py | 34 ++++++++++++++++++++++++ scrapling/fetchers.py | 19 ++++++++----- 6 files changed, 61 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 33ebbf9..d19981e 100644 --- a/README.md +++ b/README.md @@ -257,6 +257,7 @@ True | network_idle | Wait for the page until there are no network connections for at least 500 ms. | ✔️ | | timeout | The timeout in milliseconds that is used in all operations and waits through the page. The default is 30000. | ✔️ | | wait_selector | Wait for a specific css selector to be in a specific state. | ✔️ | +| proxy | The proxy to be used with requests, it can be a string or a dictionary with the keys 'server', 'username', and 'password' only. | ✔️ | | wait_selector_state | The state to wait for the selector given with `wait_selector`. _Default state is `attached`._ | ✔️ |
@@ -299,6 +300,7 @@ Add that to a lot of controlling/hiding options as you will see in the arguments | wait_selector_state | The state to wait for the selector given with `wait_selector`. _Default state is `attached`._ | ✔️ | | 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. | ✔️ | | 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. | ✔️ | +| proxy | The proxy to be used with requests, it can be a string or a dictionary with the keys 'server', 'username', and 'password' only. | ✔️ | | hide_canvas | Add random noise to canvas operations to prevent fingerprinting. | ✔️ | | disable_webgl | Disables WebGL and WebGL 2.0 support entirely. | ✔️ | | stealth | Enables stealth mode, always check the documentation to see what stealth mode does currently. | ✔️ | diff --git a/scrapling/engines/camo.py b/scrapling/engines/camo.py index 3677531..6a26495 100644 --- a/scrapling/engines/camo.py +++ b/scrapling/engines/camo.py @@ -7,6 +7,7 @@ from scrapling.engines.toolbelt import ( get_os_name, intercept_route, check_type_validity, + construct_proxy_dict, generate_convincing_referer, ) @@ -18,7 +19,8 @@ class CamoufoxEngine: self, headless: Optional[Union[bool, Literal['virtual']]] = True, block_images: Optional[bool] = False, disable_resources: Optional[bool] = False, block_webrtc: Optional[bool] = False, allow_webgl: Optional[bool] = False, network_idle: Optional[bool] = False, humanize: Optional[Union[bool, float]] = True, timeout: Optional[float] = 30000, page_action: Callable = do_nothing, wait_selector: Optional[str] = None, addons: Optional[List[str]] = None, - wait_selector_state: str = 'attached', google_search: Optional[bool] = True, extra_headers: Optional[Dict[str, str]] = None, adaptor_arguments: Dict = None + wait_selector_state: str = 'attached', google_search: Optional[bool] = True, extra_headers: Optional[Dict[str, str]] = None, + proxy: Optional[Union[str, Dict[str, str]]] = None, adaptor_arguments: Dict = None ): """An engine that utilizes Camoufox library, check the `StealthyFetcher` class for more documentation. @@ -39,6 +41,7 @@ class CamoufoxEngine: :param wait_selector_state: The state to wait for the selector given with `wait_selector`. Default state is `attached`. :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 adaptor_arguments: The arguments that will be passed in the end while creating the final Adaptor's class. """ self.headless = headless @@ -49,6 +52,7 @@ class CamoufoxEngine: self.network_idle = bool(network_idle) self.google_search = bool(google_search) self.extra_headers = extra_headers or {} + self.proxy = construct_proxy_dict(proxy) self.addons = addons or [] self.humanize = humanize self.timeout = check_type_validity(timeout, [int, float], 30000) @@ -76,6 +80,7 @@ class CamoufoxEngine: allow_webgl=self.allow_webgl, addons=self.addons, humanize=self.humanize, + proxy=self.proxy, i_know_what_im_doing=True, # To turn warnings off with user configurations ) as browser: page = browser.new_page() diff --git a/scrapling/engines/pw.py b/scrapling/engines/pw.py index 2d6ebf2..b97bcac 100644 --- a/scrapling/engines/pw.py +++ b/scrapling/engines/pw.py @@ -9,8 +9,9 @@ from scrapling.engines.toolbelt import ( js_bypass_path, intercept_route, generate_headers, - check_type_validity, construct_cdp_url, + check_type_validity, + construct_proxy_dict, generate_convincing_referer, ) @@ -33,6 +34,7 @@ class PlaywrightEngine: nstbrowser_config: Optional[Dict] = None, google_search: Optional[bool] = True, extra_headers: Optional[Dict[str, str]] = None, + proxy: Optional[Union[str, Dict[str, str]]] = None, adaptor_arguments: Dict = None ): """An engine that utilizes PlayWright library, check the `PlayWrightFetcher` class for more documentation. @@ -54,6 +56,7 @@ class PlaywrightEngine: :param nstbrowser_mode: Enables NSTBrowser mode, it have to be used with `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. """ @@ -65,6 +68,7 @@ class PlaywrightEngine: self.disable_webgl = bool(disable_webgl) 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.timeout = check_type_validity(timeout, [int, float], 30000) @@ -151,6 +155,7 @@ class PlaywrightEngine: locale='en-US', is_mobile=False, has_touch=False, + proxy=self.proxy, color_scheme='dark', # Bypasses the 'prefersLightColor' check in creepjs user_agent=useragent, device_scale_factor=2, diff --git a/scrapling/engines/toolbelt/__init__.py b/scrapling/engines/toolbelt/__init__.py index 08b559b..ac3e03d 100644 --- a/scrapling/engines/toolbelt/__init__.py +++ b/scrapling/engines/toolbelt/__init__.py @@ -15,4 +15,5 @@ from .navigation import ( js_bypass_path, intercept_route, construct_cdp_url, + construct_proxy_dict, ) diff --git a/scrapling/engines/toolbelt/navigation.py b/scrapling/engines/toolbelt/navigation.py index cf73a39..363f233 100644 --- a/scrapling/engines/toolbelt/navigation.py +++ b/scrapling/engines/toolbelt/navigation.py @@ -25,6 +25,40 @@ def intercept_route(route: Route) -> Union[Route, None]: return route.continue_() +def construct_proxy_dict(proxy_string: Union[str, Dict[str, str]]) -> Union[Dict, None]: + """Validate a proxy and return it in the acceptable format for Playwright + Reference: https://playwright.dev/python/docs/network#http-proxy + + :param proxy_string: A string or a dictionary representation of the proxy. + :return: + """ + if proxy_string: + if isinstance(proxy_string, str): + proxy = urlparse(proxy_string) + try: + return { + 'server': f'{proxy.scheme}://{proxy.hostname}:{proxy.port}', + 'username': proxy.username or '', + 'password': proxy.password or '', + } + except ValueError: + # Urllib will say that one of the parameters above can't be casted to the correct type like `int` for port etc... + raise TypeError(f'The proxy argument\'s string is in invalid format!') + + elif isinstance(proxy_string, dict): + valid_keys = ('server', 'username', 'password', ) + if all(key in valid_keys for key in proxy_string.keys()) and not any(key not in valid_keys for key in proxy_string.keys()): + return proxy_string + else: + raise TypeError(f'A proxy dictionary must have only these keys: {valid_keys}') + + else: + raise TypeError(f'Invalid type of proxy ({type(proxy_string)}), the proxy argument must be a string or a dictionary!') + + # The default value for proxy in Playwright's source is `None` + return None + + def construct_cdp_url(cdp_url: str, query_params: Optional[Dict] = None) -> str: """Takes a CDP URL, reconstruct it to check it's valid, then adds encoded parameters if exists diff --git a/scrapling/fetchers.py b/scrapling/fetchers.py index 65a8901..b0f1d60 100644 --- a/scrapling/fetchers.py +++ b/scrapling/fetchers.py @@ -72,7 +72,7 @@ class StealthyFetcher(BaseFetcher): self, url: str, headless: Optional[Union[bool, Literal['virtual']]] = True, block_images: Optional[bool] = False, disable_resources: Optional[bool] = False, block_webrtc: Optional[bool] = False, allow_webgl: Optional[bool] = False, network_idle: Optional[bool] = False, addons: Optional[List[str]] = None, timeout: Optional[float] = 30000, page_action: Callable = do_nothing, wait_selector: Optional[str] = None, humanize: Optional[Union[bool, float]] = True, - wait_selector_state: str = 'attached', google_search: Optional[bool] = True, extra_headers: Optional[Dict[str, str]] = None + wait_selector_state: str = 'attached', google_search: Optional[bool] = True, extra_headers: Optional[Dict[str, str]] = None, proxy: Optional[Union[str, Dict[str, str]]] = None, ) -> Response: """ Opens up a browser and do your request based on your chosen options below. @@ -94,23 +94,25 @@ class StealthyFetcher(BaseFetcher): :param wait_selector_state: The state to wait for the selector given with `wait_selector`. Default state is `attached`. :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. :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. """ engine = CamoufoxEngine( + proxy=proxy, + addons=addons, timeout=timeout, headless=headless, - page_action=page_action, - block_images=block_images, - block_webrtc=block_webrtc, - addons=addons, humanize=humanize, allow_webgl=allow_webgl, - disable_resources=disable_resources, + page_action=page_action, network_idle=network_idle, + block_images=block_images, + block_webrtc=block_webrtc, wait_selector=wait_selector, - wait_selector_state=wait_selector_state, google_search=google_search, extra_headers=extra_headers, + disable_resources=disable_resources, + wait_selector_state=wait_selector_state, adaptor_arguments=self.adaptor_arguments, ) return engine.fetch(url) @@ -136,6 +138,7 @@ class PlayWrightFetcher(BaseFetcher): useragent: Optional[str] = None, network_idle: Optional[bool] = False, timeout: Optional[float] = 30000, page_action: Callable = do_nothing, wait_selector: Optional[str] = None, wait_selector_state: Optional[str] = 'attached', hide_canvas: bool = True, disable_webgl: bool = False, extra_headers: Optional[Dict[str, str]] = None, google_search: Optional[bool] = True, + proxy: Optional[Union[str, Dict[str, str]]] = None, stealth: bool = False, cdp_url: Optional[str] = None, nstbrowser_mode: bool = False, nstbrowser_config: Optional[Dict] = None, @@ -157,12 +160,14 @@ class PlayWrightFetcher(BaseFetcher): :param disable_webgl: Disables WebGL and WebGL 2.0 support entirely. :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 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 have to be used with `cdp_url` argument or it will get completely ignored. :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. :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. """ engine = PlaywrightEngine( + proxy=proxy, timeout=timeout, stealth=stealth, cdp_url=cdp_url, From 5e8275c3eb5c18e4688d093f60918e610b484b1a Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Fri, 15 Nov 2024 16:36:32 +0200 Subject: [PATCH 12/13] Adding the option to randomize the OS fingerprints with the StealthyFetcher --- README.md | 3 ++- scrapling/engines/camo.py | 20 +++++++++++--------- scrapling/fetchers.py | 3 +++ 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index d19981e..14b386c 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Scrapling is a high-performance, intelligent web scraping library for Python tha ```python >> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher # Fetch websites' source under the radar! ->> page = StealthyFetcher().fetch('https://example.com', headless=True, disable_resources=True) +>> page = StealthyFetcher().fetch('https://example.com', headless=True, network_idle=True) >> print(page.status) 200 >> products = page.css('.product', auto_save=True) # Scrape data that survives website design changes! @@ -258,6 +258,7 @@ True | timeout | The timeout in milliseconds that is used in all operations and waits through the page. The default is 30000. | ✔️ | | wait_selector | Wait for a specific css selector to be in a specific state. | ✔️ | | proxy | The proxy to be used with requests, it can be a string or a dictionary with the keys 'server', 'username', and 'password' only. | ✔️ | +| os_randomize | If enabled, Scrapling will randomize the OS fingerprints used. The default is Scrapling matching the fingerprints with the current OS. | ✔️ | | wait_selector_state | The state to wait for the selector given with `wait_selector`. _Default state is `attached`._ | ✔️ | diff --git a/scrapling/engines/camo.py b/scrapling/engines/camo.py index 6a26495..19d8726 100644 --- a/scrapling/engines/camo.py +++ b/scrapling/engines/camo.py @@ -20,7 +20,7 @@ class CamoufoxEngine: block_webrtc: Optional[bool] = False, allow_webgl: Optional[bool] = False, network_idle: Optional[bool] = False, humanize: Optional[Union[bool, float]] = True, timeout: Optional[float] = 30000, page_action: Callable = do_nothing, wait_selector: Optional[str] = None, addons: Optional[List[str]] = None, wait_selector_state: str = 'attached', google_search: Optional[bool] = True, extra_headers: Optional[Dict[str, str]] = None, - proxy: Optional[Union[str, Dict[str, str]]] = None, adaptor_arguments: Dict = None + proxy: Optional[Union[str, Dict[str, str]]] = None, os_randomize: Optional[bool] = None, adaptor_arguments: Dict = None ): """An engine that utilizes Camoufox library, check the `StealthyFetcher` class for more documentation. @@ -35,6 +35,7 @@ class CamoufoxEngine: :param humanize: Humanize the cursor movement. Takes either True or the MAX duration in seconds of the cursor movement. The cursor typically takes up to 1.5 seconds to move across the window. :param allow_webgl: Whether to allow WebGL. To prevent leaks, only use this for special cases. :param network_idle: Wait for the page until there are no network connections for at least 500 ms. + :param os_randomize: If enabled, Scrapling will randomize the OS fingerprints used. The default is Scrapling matching the fingerprints with the current OS. :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30000 :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. @@ -51,6 +52,7 @@ class CamoufoxEngine: self.allow_webgl = bool(allow_webgl) self.network_idle = bool(network_idle) self.google_search = bool(google_search) + self.os_randomize = bool(os_randomize) self.extra_headers = extra_headers or {} self.proxy = construct_proxy_dict(proxy) self.addons = addons or [] @@ -73,15 +75,15 @@ class CamoufoxEngine: :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. """ with Camoufox( - headless=self.headless, - block_images=self.block_images, # Careful! it makes some websites doesn't finish loading at all like stackoverflow even in headful - os=get_os_name(), - block_webrtc=self.block_webrtc, - allow_webgl=self.allow_webgl, - addons=self.addons, - humanize=self.humanize, proxy=self.proxy, - i_know_what_im_doing=True, # To turn warnings off with user configurations + addons=self.addons, + headless=self.headless, + humanize=self.humanize, + i_know_what_im_doing=True, # To turn warnings off with the user configurations + allow_webgl=self.allow_webgl, + block_webrtc=self.block_webrtc, + block_images=self.block_images, # Careful! it makes some websites doesn't finish loading at all like stackoverflow even in headful + os=None if self.os_randomize else get_os_name(), ) as browser: page = browser.new_page() page.set_default_navigation_timeout(self.timeout) diff --git a/scrapling/fetchers.py b/scrapling/fetchers.py index b0f1d60..a63edcb 100644 --- a/scrapling/fetchers.py +++ b/scrapling/fetchers.py @@ -73,6 +73,7 @@ class StealthyFetcher(BaseFetcher): block_webrtc: Optional[bool] = False, allow_webgl: Optional[bool] = False, network_idle: Optional[bool] = False, addons: Optional[List[str]] = None, timeout: Optional[float] = 30000, page_action: Callable = do_nothing, wait_selector: Optional[str] = None, humanize: Optional[Union[bool, float]] = True, wait_selector_state: str = 'attached', google_search: Optional[bool] = True, extra_headers: Optional[Dict[str, str]] = None, proxy: Optional[Union[str, Dict[str, str]]] = None, + os_randomize: Optional[bool] = None ) -> Response: """ Opens up a browser and do your request based on your chosen options below. @@ -88,6 +89,7 @@ class StealthyFetcher(BaseFetcher): :param humanize: Humanize the cursor movement. Takes either True or the MAX duration in seconds of the cursor movement. The cursor typically takes up to 1.5 seconds to move across the window. :param allow_webgl: Whether to allow WebGL. To prevent leaks, only use this for special cases. :param network_idle: Wait for the page until there are no network connections for at least 500 ms. + :param os_randomize: If enabled, Scrapling will randomize the OS fingerprints used. The default is Scrapling matching the fingerprints with the current OS. :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30000 :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. @@ -108,6 +110,7 @@ class StealthyFetcher(BaseFetcher): network_idle=network_idle, block_images=block_images, block_webrtc=block_webrtc, + os_randomize=os_randomize, wait_selector=wait_selector, google_search=google_search, extra_headers=extra_headers, From 90e38af55258a1f807d21e2e291e3662de66e468 Mon Sep 17 00:00:00 2001 From: Karim shoair Date: Fri, 15 Nov 2024 16:44:47 +0200 Subject: [PATCH 13/13] Correcting the return string for the `Response` object in all functions/methods --- scrapling/engines/camo.py | 2 +- scrapling/engines/pw.py | 2 +- scrapling/engines/static.py | 10 +++++----- scrapling/fetchers.py | 12 ++++++------ 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/scrapling/engines/camo.py b/scrapling/engines/camo.py index 19d8726..4131151 100644 --- a/scrapling/engines/camo.py +++ b/scrapling/engines/camo.py @@ -72,7 +72,7 @@ class CamoufoxEngine: """Opens up the browser and do your request based on your chosen options. :param url: Target url. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ with Camoufox( proxy=self.proxy, diff --git a/scrapling/engines/pw.py b/scrapling/engines/pw.py index b97bcac..6c80900 100644 --- a/scrapling/engines/pw.py +++ b/scrapling/engines/pw.py @@ -116,7 +116,7 @@ class PlaywrightEngine: """Opens up the browser and do your request based on your chosen options. :param url: Target url. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ if not self.stealth: from playwright.sync_api import sync_playwright diff --git a/scrapling/engines/static.py b/scrapling/engines/static.py index ffc8822..d424752 100644 --- a/scrapling/engines/static.py +++ b/scrapling/engines/static.py @@ -48,7 +48,7 @@ class StaticEngine: """Takes httpx response and generates `Response` object from it. :param response: httpx response object - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :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 Response( url=str(response.url), @@ -69,7 +69,7 @@ class StaticEngine: :param stealthy_headers: If enabled (default), Fetcher will create and add real browser's headers and create a referer header as if this request had came from Google's search of this URL's domain. :param kwargs: Any additional keyword arguments are passed directly to `httpx.get()` function so check httpx documentation for details. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ headers = self._headers_job(kwargs.pop('headers', {}), url, stealthy_headers) request = httpx.get(url=url, headers=headers, follow_redirects=self.follow_redirects, timeout=self.timeout, **kwargs) @@ -81,7 +81,7 @@ class StaticEngine: :param stealthy_headers: If enabled (default), Fetcher will create and add real browser's headers and create a referer header as if this request had came from Google's search of this URL's domain. :param kwargs: Any additional keyword arguments are passed directly to `httpx.post()` function so check httpx documentation for details. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ headers = self._headers_job(kwargs.pop('headers', {}), url, stealthy_headers) request = httpx.post(url=url, headers=headers, follow_redirects=self.follow_redirects, timeout=self.timeout, **kwargs) @@ -93,7 +93,7 @@ class StaticEngine: :param stealthy_headers: If enabled (default), Fetcher will create and add real browser's headers and create a referer header as if this request had came from Google's search of this URL's domain. :param kwargs: Any additional keyword arguments are passed directly to `httpx.delete()` function so check httpx documentation for details. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ headers = self._headers_job(kwargs.pop('headers', {}), url, stealthy_headers) request = httpx.delete(url=url, headers=headers, follow_redirects=self.follow_redirects, timeout=self.timeout, **kwargs) @@ -105,7 +105,7 @@ class StaticEngine: :param stealthy_headers: If enabled (default), Fetcher will create and add real browser's headers and create a referer header as if this request had came from Google's search of this URL's domain. :param kwargs: Any additional keyword arguments are passed directly to `httpx.put()` function so check httpx documentation for details. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ headers = self._headers_job(kwargs.pop('headers', {}), url, stealthy_headers) request = httpx.put(url=url, headers=headers, follow_redirects=self.follow_redirects, timeout=self.timeout, **kwargs) diff --git a/scrapling/fetchers.py b/scrapling/fetchers.py index a63edcb..294baca 100644 --- a/scrapling/fetchers.py +++ b/scrapling/fetchers.py @@ -17,7 +17,7 @@ class Fetcher(BaseFetcher): :param stealthy_headers: If enabled (default), Fetcher will create and add real browser's headers and create a referer header as if this request had came from Google's search of this URL's domain. :param kwargs: Any additional keyword arguments are passed directly to `httpx.get()` function so check httpx documentation for details. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ response_object = StaticEngine(follow_redirects, timeout, adaptor_arguments=self.adaptor_arguments).get(url, stealthy_headers, **kwargs) return response_object @@ -30,7 +30,7 @@ class Fetcher(BaseFetcher): :param stealthy_headers: If enabled (default), Fetcher will create and add real browser's headers and create a referer header as if this request came from Google's search of this URL's domain. :param kwargs: Any additional keyword arguments are passed directly to `httpx.post()` function so check httpx documentation for details. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ response_object = StaticEngine(follow_redirects, timeout, adaptor_arguments=self.adaptor_arguments).post(url, stealthy_headers, **kwargs) return response_object @@ -43,7 +43,7 @@ class Fetcher(BaseFetcher): :param stealthy_headers: If enabled (default), Fetcher will create and add real browser's headers and create a referer header as if this request came from Google's search of this URL's domain. :param kwargs: Any additional keyword arguments are passed directly to `httpx.put()` function so check httpx documentation for details. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ response_object = StaticEngine(follow_redirects, timeout, adaptor_arguments=self.adaptor_arguments).put(url, stealthy_headers, **kwargs) return response_object @@ -56,7 +56,7 @@ class Fetcher(BaseFetcher): :param stealthy_headers: If enabled (default), Fetcher will create and add real browser's headers and create a referer header as if this request came from Google's search of this URL's domain. :param kwargs: Any additional keyword arguments are passed directly to `httpx.delete()` function so check httpx documentation for details. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ response_object = StaticEngine(follow_redirects, timeout, adaptor_arguments=self.adaptor_arguments).delete(url, stealthy_headers, **kwargs) return response_object @@ -97,7 +97,7 @@ class StealthyFetcher(BaseFetcher): :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. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ engine = CamoufoxEngine( proxy=proxy, @@ -167,7 +167,7 @@ class PlayWrightFetcher(BaseFetcher): :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 have to be used with `cdp_url` argument or it will get completely ignored. :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. - :return: A Response object with `url`, `text`, `content`, `status`, `reason`, `encoding`, `cookies`, `headers`, `request_headers`, and the `adaptor` class for parsing, of course. + :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers` """ engine = PlaywrightEngine( proxy=proxy,