scrapling 0.2.98__py3-none-any.whl → 0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. scrapling/__init__.py +18 -31
  2. scrapling/cli.py +818 -20
  3. scrapling/core/_html_utils.py +348 -0
  4. scrapling/core/_types.py +34 -17
  5. scrapling/core/ai.py +611 -0
  6. scrapling/core/custom_types.py +183 -100
  7. scrapling/core/mixins.py +27 -19
  8. scrapling/core/shell.py +647 -0
  9. scrapling/core/{storage_adaptors.py → storage.py} +41 -33
  10. scrapling/core/translator.py +20 -26
  11. scrapling/core/utils.py +49 -54
  12. scrapling/engines/__init__.py +15 -6
  13. scrapling/engines/_browsers/__init__.py +2 -0
  14. scrapling/engines/_browsers/_camoufox.py +745 -0
  15. scrapling/engines/_browsers/_config_tools.py +130 -0
  16. scrapling/engines/_browsers/_controllers.py +630 -0
  17. scrapling/engines/_browsers/_page.py +93 -0
  18. scrapling/engines/_browsers/_validators.py +150 -0
  19. scrapling/engines/constants.py +101 -88
  20. scrapling/engines/static.py +667 -110
  21. scrapling/engines/toolbelt/__init__.py +20 -6
  22. scrapling/engines/toolbelt/bypasses/playwright_fingerprint.js +2 -1
  23. scrapling/engines/toolbelt/convertor.py +254 -0
  24. scrapling/engines/toolbelt/custom.py +205 -186
  25. scrapling/engines/toolbelt/fingerprints.py +32 -46
  26. scrapling/engines/toolbelt/navigation.py +68 -39
  27. scrapling/fetchers.py +255 -260
  28. scrapling/parser.py +781 -449
  29. scrapling-0.3.dist-info/METADATA +409 -0
  30. scrapling-0.3.dist-info/RECORD +41 -0
  31. {scrapling-0.2.98.dist-info → scrapling-0.3.dist-info}/WHEEL +1 -1
  32. {scrapling-0.2.98.dist-info → scrapling-0.3.dist-info}/top_level.txt +0 -1
  33. scrapling/defaults.py +0 -19
  34. scrapling/engines/camo.py +0 -299
  35. scrapling/engines/pw.py +0 -428
  36. scrapling/engines/toolbelt/bypasses/pdf_viewer.js +0 -5
  37. scrapling-0.2.98.dist-info/METADATA +0 -867
  38. scrapling-0.2.98.dist-info/RECORD +0 -49
  39. tests/__init__.py +0 -1
  40. tests/fetchers/__init__.py +0 -1
  41. tests/fetchers/async/__init__.py +0 -0
  42. tests/fetchers/async/test_camoufox.py +0 -95
  43. tests/fetchers/async/test_httpx.py +0 -83
  44. tests/fetchers/async/test_playwright.py +0 -99
  45. tests/fetchers/sync/__init__.py +0 -0
  46. tests/fetchers/sync/test_camoufox.py +0 -68
  47. tests/fetchers/sync/test_httpx.py +0 -82
  48. tests/fetchers/sync/test_playwright.py +0 -87
  49. tests/fetchers/test_utils.py +0 -97
  50. tests/parser/__init__.py +0 -0
  51. tests/parser/test_automatch.py +0 -111
  52. tests/parser/test_general.py +0 -330
  53. {scrapling-0.2.98.dist-info → scrapling-0.3.dist-info}/entry_points.txt +0 -0
  54. {scrapling-0.2.98.dist-info → scrapling-0.3.dist-info/licenses}/LICENSE +0 -0
scrapling/engines/camo.py DELETED
@@ -1,299 +0,0 @@
1
- from camoufox import DefaultAddons
2
- from camoufox.async_api import AsyncCamoufox
3
- from camoufox.sync_api import Camoufox
4
-
5
- from scrapling.core._types import (Callable, Dict, List, Literal, Optional,
6
- SelectorWaitStates, Union)
7
- from scrapling.core.utils import log
8
- from scrapling.engines.toolbelt import (Response, StatusText,
9
- async_intercept_route,
10
- check_type_validity,
11
- construct_proxy_dict,
12
- generate_convincing_referer,
13
- get_os_name, intercept_route)
14
-
15
-
16
- class CamoufoxEngine:
17
- def __init__(
18
- self, headless: Union[bool, Literal['virtual']] = True, block_images: bool = False, disable_resources: bool = False,
19
- block_webrtc: bool = False, allow_webgl: bool = True, network_idle: bool = False, humanize: Union[bool, float] = True,
20
- timeout: Optional[float] = 30000, page_action: Callable = None, wait_selector: Optional[str] = None, addons: Optional[List[str]] = None,
21
- wait_selector_state: SelectorWaitStates = 'attached', google_search: bool = True, extra_headers: Optional[Dict[str, str]] = None,
22
- proxy: Optional[Union[str, Dict[str, str]]] = None, os_randomize: bool = False, disable_ads: bool = False,
23
- geoip: bool = False,
24
- adaptor_arguments: Dict = None,
25
- ):
26
- """An engine that utilizes Camoufox library, check the `StealthyFetcher` class for more documentation.
27
-
28
- :param headless: Run the browser in headless/hidden (default), virtual screen mode, or headful/visible mode.
29
- :param block_images: Prevent the loading of images through Firefox preferences.
30
- This can help save your proxy usage but be careful with this option as it makes some websites never finish loading.
31
- :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.
32
- Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`.
33
- This can help save your proxy usage but be careful with this option as it makes some websites never finish loading.
34
- :param block_webrtc: Blocks WebRTC entirely.
35
- :param addons: List of Firefox addons to use. Must be paths to extracted addons.
36
- :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.
37
- :param allow_webgl: Enabled by default. Disabling it WebGL not recommended as many WAFs now checks if WebGL is enabled.
38
- :param network_idle: Wait for the page until there are no network connections for at least 500 ms.
39
- :param disable_ads: Disabled by default, this installs `uBlock Origin` addon on the browser if enabled.
40
- :param os_randomize: If enabled, Scrapling will randomize the OS fingerprints used. The default is Scrapling matching the fingerprints with the current OS.
41
- :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30000
42
- :param page_action: Added for automation. A function that takes the `page` object, does the automation you need, then returns `page` again.
43
- :param wait_selector: Wait for a specific css selector to be in a specific state.
44
- :param geoip: Recommended to use with proxies; Automatically use IP's longitude, latitude, timezone, country, locale, & spoof the WebRTC IP address.
45
- It will also calculate and spoof the browser's language based on the distribution of language speakers in the target region.
46
- :param wait_selector_state: The state to wait for the selector given with `wait_selector`. Default state is `attached`.
47
- :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.
48
- :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._
49
- :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.
50
- :param adaptor_arguments: The arguments that will be passed in the end while creating the final Adaptor's class.
51
- """
52
- self.headless = headless
53
- self.block_images = bool(block_images)
54
- self.disable_resources = bool(disable_resources)
55
- self.block_webrtc = bool(block_webrtc)
56
- self.allow_webgl = bool(allow_webgl)
57
- self.network_idle = bool(network_idle)
58
- self.google_search = bool(google_search)
59
- self.os_randomize = bool(os_randomize)
60
- self.disable_ads = bool(disable_ads)
61
- self.geoip = bool(geoip)
62
- self.extra_headers = extra_headers or {}
63
- self.proxy = construct_proxy_dict(proxy)
64
- self.addons = addons or []
65
- self.humanize = humanize
66
- self.timeout = check_type_validity(timeout, [int, float], 30000)
67
-
68
- # Page action callable validation
69
- self.page_action = None
70
- if page_action is not None:
71
- if callable(page_action):
72
- self.page_action = page_action
73
- else:
74
- log.error('[Ignored] Argument "page_action" must be callable')
75
-
76
- self.wait_selector = wait_selector
77
- self.wait_selector_state = wait_selector_state
78
- self.adaptor_arguments = adaptor_arguments if adaptor_arguments else {}
79
-
80
- def _get_camoufox_options(self):
81
- """Return consistent browser options dictionary for both sync and async methods"""
82
- return {
83
- "geoip": self.geoip,
84
- "proxy": self.proxy,
85
- "enable_cache": True,
86
- "addons": self.addons,
87
- "exclude_addons": [] if self.disable_ads else [DefaultAddons.UBO],
88
- "headless": self.headless,
89
- "humanize": self.humanize,
90
- "i_know_what_im_doing": True, # To turn warnings off with the user configurations
91
- "allow_webgl": self.allow_webgl,
92
- "block_webrtc": self.block_webrtc,
93
- "block_images": self.block_images, # Careful! it makes some websites doesn't finish loading at all like stackoverflow even in headful
94
- "os": None if self.os_randomize else get_os_name(),
95
- }
96
-
97
- def _process_response_history(self, first_response):
98
- """Process response history to build a list of Response objects"""
99
- history = []
100
- current_request = first_response.request.redirected_from
101
-
102
- try:
103
- while current_request:
104
- try:
105
- current_response = current_request.response()
106
- history.insert(0, Response(
107
- url=current_request.url,
108
- # using current_response.text() will trigger "Error: Response.text: Response body is unavailable for redirect responses"
109
- text='',
110
- body=b'',
111
- status=current_response.status if current_response else 301,
112
- reason=(current_response.status_text or StatusText.get(current_response.status)) if current_response else StatusText.get(301),
113
- encoding=current_response.headers.get('content-type', '') or 'utf-8',
114
- cookies={},
115
- headers=current_response.all_headers() if current_response else {},
116
- request_headers=current_request.all_headers(),
117
- **self.adaptor_arguments
118
- ))
119
- except Exception as e:
120
- log.error(f"Error processing redirect: {e}")
121
- break
122
-
123
- current_request = current_request.redirected_from
124
- except Exception as e:
125
- log.error(f"Error processing response history: {e}")
126
-
127
- return history
128
-
129
- def fetch(self, url: str) -> Response:
130
- """Opens up the browser and do your request based on your chosen options.
131
-
132
- :param url: Target url.
133
- :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers`
134
- """
135
- final_response = None
136
- referer = generate_convincing_referer(url) if self.google_search else None
137
-
138
- def handle_response(finished_response):
139
- nonlocal final_response
140
- if finished_response.request.resource_type == "document" and finished_response.request.is_navigation_request():
141
- final_response = finished_response
142
-
143
- with Camoufox(**self._get_camoufox_options()) as browser:
144
- context = browser.new_context()
145
- page = context.new_page()
146
- page.set_default_navigation_timeout(self.timeout)
147
- page.set_default_timeout(self.timeout)
148
- page.on("response", handle_response)
149
-
150
- if self.disable_resources:
151
- page.route("**/*", intercept_route)
152
-
153
- if self.extra_headers:
154
- page.set_extra_http_headers(self.extra_headers)
155
-
156
- first_response = page.goto(url, referer=referer)
157
- page.wait_for_load_state(state="domcontentloaded")
158
-
159
- if self.network_idle:
160
- page.wait_for_load_state('networkidle')
161
-
162
- if self.page_action is not None:
163
- try:
164
- page = self.page_action(page)
165
- except Exception as e:
166
- log.error(f"Error executing page_action: {e}")
167
-
168
- if self.wait_selector and type(self.wait_selector) is str:
169
- try:
170
- waiter = page.locator(self.wait_selector)
171
- waiter.first.wait_for(state=self.wait_selector_state)
172
- # Wait again after waiting for the selector, helpful with protections like Cloudflare
173
- page.wait_for_load_state(state="load")
174
- page.wait_for_load_state(state="domcontentloaded")
175
- if self.network_idle:
176
- page.wait_for_load_state('networkidle')
177
- except Exception as e:
178
- log.error(f"Error waiting for selector {self.wait_selector}: {e}")
179
-
180
- # In case we didn't catch a document type somehow
181
- final_response = final_response if final_response else first_response
182
- if not final_response:
183
- raise ValueError("Failed to get a response from the page")
184
-
185
- # This will be parsed inside `Response`
186
- encoding = final_response.headers.get('content-type', '') or 'utf-8' # default encoding
187
- # PlayWright API sometimes give empty status text for some reason!
188
- status_text = final_response.status_text or StatusText.get(final_response.status)
189
-
190
- history = self._process_response_history(first_response)
191
- try:
192
- page_content = page.content()
193
- except Exception as e:
194
- log.error(f"Error getting page content: {e}")
195
- page_content = ""
196
-
197
- response = Response(
198
- url=page.url,
199
- text=page_content,
200
- body=page_content.encode('utf-8'),
201
- status=final_response.status,
202
- reason=status_text,
203
- encoding=encoding,
204
- cookies={cookie['name']: cookie['value'] for cookie in page.context.cookies()},
205
- headers=first_response.all_headers(),
206
- request_headers=first_response.request.all_headers(),
207
- history=history,
208
- **self.adaptor_arguments
209
- )
210
- page.close()
211
- context.close()
212
-
213
- return response
214
-
215
- async def async_fetch(self, url: str) -> Response:
216
- """Opens up the browser and do your request based on your chosen options.
217
-
218
- :param url: Target url.
219
- :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers`
220
- """
221
- final_response = None
222
- referer = generate_convincing_referer(url) if self.google_search else None
223
-
224
- async def handle_response(finished_response):
225
- nonlocal final_response
226
- if finished_response.request.resource_type == "document" and finished_response.request.is_navigation_request():
227
- final_response = finished_response
228
-
229
- async with AsyncCamoufox(**self._get_camoufox_options()) as browser:
230
- context = await browser.new_context()
231
- page = await context.new_page()
232
- page.set_default_navigation_timeout(self.timeout)
233
- page.set_default_timeout(self.timeout)
234
- page.on("response", handle_response)
235
-
236
- if self.disable_resources:
237
- await page.route("**/*", async_intercept_route)
238
-
239
- if self.extra_headers:
240
- await page.set_extra_http_headers(self.extra_headers)
241
-
242
- first_response = await page.goto(url, referer=referer)
243
- await page.wait_for_load_state(state="domcontentloaded")
244
-
245
- if self.network_idle:
246
- await page.wait_for_load_state('networkidle')
247
-
248
- if self.page_action is not None:
249
- try:
250
- page = await self.page_action(page)
251
- except Exception as e:
252
- log.error(f"Error executing async page_action: {e}")
253
-
254
- if self.wait_selector and type(self.wait_selector) is str:
255
- try:
256
- waiter = page.locator(self.wait_selector)
257
- await waiter.first.wait_for(state=self.wait_selector_state)
258
- # Wait again after waiting for the selector, helpful with protections like Cloudflare
259
- await page.wait_for_load_state(state="load")
260
- await page.wait_for_load_state(state="domcontentloaded")
261
- if self.network_idle:
262
- await page.wait_for_load_state('networkidle')
263
- except Exception as e:
264
- log.error(f"Error waiting for selector {self.wait_selector}: {e}")
265
-
266
- # In case we didn't catch a document type somehow
267
- final_response = final_response if final_response else first_response
268
- if not final_response:
269
- raise ValueError("Failed to get a response from the page")
270
-
271
- # This will be parsed inside `Response`
272
- encoding = final_response.headers.get('content-type', '') or 'utf-8' # default encoding
273
- # PlayWright API sometimes give empty status text for some reason!
274
- status_text = final_response.status_text or StatusText.get(final_response.status)
275
-
276
- history = self._process_response_history(first_response)
277
- try:
278
- page_content = await page.content()
279
- except Exception as e:
280
- log.error(f"Error getting page content in async: {e}")
281
- page_content = ""
282
-
283
- response = Response(
284
- url=page.url,
285
- text=page_content,
286
- body=page_content.encode('utf-8'),
287
- status=final_response.status,
288
- reason=status_text,
289
- encoding=encoding,
290
- cookies={cookie['name']: cookie['value'] for cookie in await page.context.cookies()},
291
- headers=await first_response.all_headers(),
292
- request_headers=await first_response.request.all_headers(),
293
- history=history,
294
- **self.adaptor_arguments
295
- )
296
- await page.close()
297
- await context.close()
298
-
299
- return response