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/pw.py DELETED
@@ -1,428 +0,0 @@
1
- import json
2
-
3
- from scrapling.core._types import (Callable, Dict, Optional,
4
- SelectorWaitStates, Union)
5
- from scrapling.core.utils import log, lru_cache
6
- from scrapling.engines.constants import (DEFAULT_STEALTH_FLAGS,
7
- NSTBROWSER_DEFAULT_QUERY)
8
- from scrapling.engines.toolbelt import (Response, StatusText,
9
- async_intercept_route,
10
- check_type_validity, construct_cdp_url,
11
- construct_proxy_dict,
12
- generate_convincing_referer,
13
- generate_headers, intercept_route,
14
- js_bypass_path)
15
-
16
-
17
- class PlaywrightEngine:
18
- def __init__(
19
- self, headless: Union[bool, str] = True,
20
- disable_resources: bool = False,
21
- useragent: Optional[str] = None,
22
- network_idle: bool = False,
23
- timeout: Optional[float] = 30000,
24
- page_action: Callable = None,
25
- wait_selector: Optional[str] = None,
26
- locale: Optional[str] = 'en-US',
27
- wait_selector_state: SelectorWaitStates = 'attached',
28
- stealth: bool = False,
29
- real_chrome: bool = False,
30
- hide_canvas: bool = False,
31
- disable_webgl: bool = False,
32
- cdp_url: Optional[str] = None,
33
- nstbrowser_mode: bool = False,
34
- nstbrowser_config: Optional[Dict] = None,
35
- google_search: bool = True,
36
- extra_headers: Optional[Dict[str, str]] = None,
37
- proxy: Optional[Union[str, Dict[str, str]]] = None,
38
- adaptor_arguments: Dict = None
39
- ):
40
- """An engine that utilizes PlayWright library, check the `PlayWrightFetcher` class for more documentation.
41
-
42
- :param headless: Run the browser in headless/hidden (default), or headful/visible mode.
43
- :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.
44
- Requests dropped are of type `font`, `image`, `media`, `beacon`, `object`, `imageset`, `texttrack`, `websocket`, `csp_report`, and `stylesheet`.
45
- This can help save your proxy usage but be careful with this option as it makes some websites never finish loading.
46
- :param useragent: Pass a useragent string to be used. Otherwise the fetcher will generate a real Useragent of the same browser and use it.
47
- :param network_idle: Wait for the page until there are no network connections for at least 500 ms.
48
- :param timeout: The timeout in milliseconds that is used in all operations and waits through the page. The default is 30000
49
- :param page_action: Added for automation. A function that takes the `page` object, does the automation you need, then returns `page` again.
50
- :param wait_selector: Wait for a specific css selector to be in a specific state.
51
- :param locale: Set the locale for the browser if wanted. The default value is `en-US`.
52
- :param wait_selector_state: The state to wait for the selector given with `wait_selector`. Default state is `attached`.
53
- :param stealth: Enables stealth mode, check the documentation to see what stealth mode does currently.
54
- :param real_chrome: If you have chrome browser installed on your device, enable this and the Fetcher will launch an instance of your browser and use it.
55
- :param hide_canvas: Add random noise to canvas operations to prevent fingerprinting.
56
- :param disable_webgl: Disables WebGL and WebGL 2.0 support entirely.
57
- :param cdp_url: Instead of launching a new browser instance, connect to this CDP URL to control real browsers/NSTBrowser through CDP.
58
- :param nstbrowser_mode: Enables NSTBrowser mode, it have to be used with `cdp_url` argument or it will get completely ignored.
59
- :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.
60
- :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._
61
- :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.
62
- :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.
63
- :param adaptor_arguments: The arguments that will be passed in the end while creating the final Adaptor's class.
64
- """
65
- self.headless = headless
66
- self.locale = check_type_validity(locale, [str], 'en-US', param_name='locale')
67
- self.disable_resources = disable_resources
68
- self.network_idle = bool(network_idle)
69
- self.stealth = bool(stealth)
70
- self.hide_canvas = bool(hide_canvas)
71
- self.disable_webgl = bool(disable_webgl)
72
- self.real_chrome = bool(real_chrome)
73
- self.google_search = bool(google_search)
74
- self.extra_headers = extra_headers or {}
75
- self.proxy = construct_proxy_dict(proxy)
76
- self.cdp_url = cdp_url
77
- self.useragent = useragent
78
- self.timeout = check_type_validity(timeout, [int, float], 30000)
79
- if page_action is not None:
80
- if callable(page_action):
81
- self.page_action = page_action
82
- else:
83
- self.page_action = None
84
- log.error('[Ignored] Argument "page_action" must be callable')
85
- else:
86
- self.page_action = None
87
-
88
- self.wait_selector = wait_selector
89
- self.wait_selector_state = wait_selector_state
90
- self.nstbrowser_mode = bool(nstbrowser_mode)
91
- self.nstbrowser_config = nstbrowser_config
92
- self.adaptor_arguments = adaptor_arguments if adaptor_arguments else {}
93
- self.harmful_default_args = [
94
- # This will be ignored to avoid detection more and possibly avoid the popup crashing bug abuse: https://issues.chromium.org/issues/340836884
95
- '--enable-automation',
96
- '--disable-popup-blocking',
97
- # '--disable-component-update',
98
- # '--disable-default-apps',
99
- # '--disable-extensions',
100
- ]
101
-
102
- def _cdp_url_logic(self) -> str:
103
- """Constructs new CDP URL if NSTBrowser is enabled otherwise return CDP URL as it is
104
- :return: CDP URL
105
- """
106
- cdp_url = self.cdp_url
107
- if self.nstbrowser_mode:
108
- if self.nstbrowser_config and isinstance(self.nstbrowser_config, dict):
109
- config = self.nstbrowser_config
110
- else:
111
- query = NSTBROWSER_DEFAULT_QUERY.copy()
112
- if self.stealth:
113
- flags = self.__set_flags()
114
- query.update({
115
- "args": dict(zip(flags, [''] * len(flags))), # browser args should be a dictionary
116
- })
117
-
118
- config = {
119
- 'config': json.dumps(query),
120
- # 'token': ''
121
- }
122
- cdp_url = construct_cdp_url(cdp_url, config)
123
- else:
124
- # To validate it
125
- cdp_url = construct_cdp_url(cdp_url)
126
-
127
- return cdp_url
128
-
129
- @lru_cache(32, typed=True)
130
- def __set_flags(self):
131
- """Returns the flags that will be used while launching the browser if stealth mode is enabled"""
132
- flags = DEFAULT_STEALTH_FLAGS
133
- if self.hide_canvas:
134
- flags += ('--fingerprinting-canvas-image-data-noise',)
135
- if self.disable_webgl:
136
- flags += ('--disable-webgl', '--disable-webgl-image-chromium', '--disable-webgl2',)
137
-
138
- return flags
139
-
140
- def __launch_kwargs(self):
141
- """Creates the arguments we will use while launching playwright's browser"""
142
- launch_kwargs = {'headless': self.headless, 'ignore_default_args': self.harmful_default_args, 'channel': 'chrome' if self.real_chrome else 'chromium'}
143
- if self.stealth:
144
- launch_kwargs.update({'args': self.__set_flags(), 'chromium_sandbox': True})
145
-
146
- return launch_kwargs
147
-
148
- def __context_kwargs(self):
149
- """Creates the arguments for the browser context"""
150
- context_kwargs = {
151
- "proxy": self.proxy,
152
- "locale": self.locale,
153
- "color_scheme": 'dark', # Bypasses the 'prefersLightColor' check in creepjs
154
- "device_scale_factor": 2,
155
- "extra_http_headers": self.extra_headers if self.extra_headers else {},
156
- "user_agent": self.useragent if self.useragent else generate_headers(browser_mode=True).get('User-Agent'),
157
- }
158
- if self.stealth:
159
- context_kwargs.update({
160
- 'is_mobile': False,
161
- 'has_touch': False,
162
- # I'm thinking about disabling it to rest from all Service Workers headache but let's keep it as it is for now
163
- 'service_workers': 'allow',
164
- 'ignore_https_errors': True,
165
- 'screen': {'width': 1920, 'height': 1080},
166
- 'viewport': {'width': 1920, 'height': 1080},
167
- 'permissions': ['geolocation', 'notifications']
168
- })
169
-
170
- return context_kwargs
171
-
172
- @lru_cache(1)
173
- def __stealth_scripts(self):
174
- # Basic bypasses nothing fancy as I'm still working on it
175
- # But with adding these bypasses to the above config, it bypasses many online tests like
176
- # https://bot.sannysoft.com/
177
- # https://kaliiiiiiiiii.github.io/brotector/
178
- # https://pixelscan.net/
179
- # https://iphey.com/
180
- # https://www.browserscan.net/bot-detection <== this one also checks for the CDP runtime fingerprint
181
- # https://arh.antoinevastel.com/bots/areyouheadless/
182
- # https://prescience-data.github.io/execution-monitor.html
183
- return tuple(
184
- js_bypass_path(script) for script in (
185
- # Order is important
186
- 'webdriver_fully.js', 'window_chrome.js', 'navigator_plugins.js', 'pdf_viewer.js',
187
- 'notification_permission.js', 'screen_props.js', 'playwright_fingerprint.js'
188
- )
189
- )
190
-
191
- def _process_response_history(self, first_response):
192
- """Process response history to build a list of Response objects"""
193
- history = []
194
- current_request = first_response.request.redirected_from
195
-
196
- try:
197
- while current_request:
198
- try:
199
- current_response = current_request.response()
200
- history.insert(0, Response(
201
- url=current_request.url,
202
- # using current_response.text() will trigger "Error: Response.text: Response body is unavailable for redirect responses"
203
- text='',
204
- body=b'',
205
- status=current_response.status if current_response else 301,
206
- reason=(current_response.status_text or StatusText.get(current_response.status)) if current_response else StatusText.get(301),
207
- encoding=current_response.headers.get('content-type', '') or 'utf-8',
208
- cookies={},
209
- headers=current_response.all_headers() if current_response else {},
210
- request_headers=current_request.all_headers(),
211
- **self.adaptor_arguments
212
- ))
213
- except Exception as e:
214
- log.error(f"Error processing redirect: {e}")
215
- break
216
-
217
- current_request = current_request.redirected_from
218
- except Exception as e:
219
- log.error(f"Error processing response history: {e}")
220
-
221
- return history
222
-
223
- def fetch(self, url: str) -> Response:
224
- """Opens up the browser and do your request based on your chosen options.
225
-
226
- :param url: Target url.
227
- :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers`
228
- """
229
- from playwright.sync_api import Response as PlaywrightResponse
230
- if not self.stealth or self.real_chrome:
231
- # Because rebrowser_playwright doesn't play well with real browsers
232
- from playwright.sync_api import sync_playwright
233
- else:
234
- from rebrowser_playwright.sync_api import sync_playwright
235
-
236
- final_response = None
237
- referer = generate_convincing_referer(url) if self.google_search else None
238
-
239
- def handle_response(finished_response: PlaywrightResponse):
240
- nonlocal final_response
241
- if finished_response.request.resource_type == "document" and finished_response.request.is_navigation_request():
242
- final_response = finished_response
243
-
244
- with sync_playwright() as p:
245
- # Creating the browser
246
- if self.cdp_url:
247
- cdp_url = self._cdp_url_logic()
248
- browser = p.chromium.connect_over_cdp(endpoint_url=cdp_url)
249
- else:
250
- browser = p.chromium.launch(**self.__launch_kwargs())
251
-
252
- context = browser.new_context(**self.__context_kwargs())
253
- page = context.new_page()
254
- page.set_default_navigation_timeout(self.timeout)
255
- page.set_default_timeout(self.timeout)
256
- page.on("response", handle_response)
257
-
258
- if self.extra_headers:
259
- page.set_extra_http_headers(self.extra_headers)
260
-
261
- if self.disable_resources:
262
- page.route("**/*", intercept_route)
263
-
264
- if self.stealth:
265
- for script in self.__stealth_scripts():
266
- page.add_init_script(path=script)
267
-
268
- first_response = page.goto(url, referer=referer)
269
- page.wait_for_load_state(state="domcontentloaded")
270
-
271
- if self.network_idle:
272
- page.wait_for_load_state('networkidle')
273
-
274
- if self.page_action is not None:
275
- try:
276
- page = self.page_action(page)
277
- except Exception as e:
278
- log.error(f"Error executing page_action: {e}")
279
-
280
- if self.wait_selector and type(self.wait_selector) is str:
281
- try:
282
- waiter = page.locator(self.wait_selector)
283
- waiter.first.wait_for(state=self.wait_selector_state)
284
- # Wait again after waiting for the selector, helpful with protections like Cloudflare
285
- page.wait_for_load_state(state="load")
286
- page.wait_for_load_state(state="domcontentloaded")
287
- if self.network_idle:
288
- page.wait_for_load_state('networkidle')
289
- except Exception as e:
290
- log.error(f"Error waiting for selector {self.wait_selector}: {e}")
291
-
292
- # In case we didn't catch a document type somehow
293
- final_response = final_response if final_response else first_response
294
- if not final_response:
295
- raise ValueError("Failed to get a response from the page")
296
-
297
- # This will be parsed inside `Response`
298
- encoding = final_response.headers.get('content-type', '') or 'utf-8' # default encoding
299
- # PlayWright API sometimes give empty status text for some reason!
300
- status_text = final_response.status_text or StatusText.get(final_response.status)
301
-
302
- history = self._process_response_history(first_response)
303
- try:
304
- page_content = page.content()
305
- except Exception as e:
306
- log.error(f"Error getting page content: {e}")
307
- page_content = ""
308
-
309
- response = Response(
310
- url=page.url,
311
- text=page_content,
312
- body=page_content.encode('utf-8'),
313
- status=final_response.status,
314
- reason=status_text,
315
- encoding=encoding,
316
- cookies={cookie['name']: cookie['value'] for cookie in page.context.cookies()},
317
- headers=first_response.all_headers(),
318
- request_headers=first_response.request.all_headers(),
319
- history=history,
320
- **self.adaptor_arguments
321
- )
322
- page.close()
323
- context.close()
324
- return response
325
-
326
- async def async_fetch(self, url: str) -> Response:
327
- """Async version of `fetch`
328
-
329
- :param url: Target url.
330
- :return: A `Response` object that is the same as `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers`
331
- """
332
- from playwright.async_api import Response as PlaywrightResponse
333
- if not self.stealth or self.real_chrome:
334
- # Because rebrowser_playwright doesn't play well with real browsers
335
- from playwright.async_api import async_playwright
336
- else:
337
- from rebrowser_playwright.async_api import async_playwright
338
-
339
- final_response = None
340
- referer = generate_convincing_referer(url) if self.google_search else None
341
-
342
- async def handle_response(finished_response: PlaywrightResponse):
343
- nonlocal final_response
344
- if finished_response.request.resource_type == "document" and finished_response.request.is_navigation_request():
345
- final_response = finished_response
346
-
347
- async with async_playwright() as p:
348
- # Creating the browser
349
- if self.cdp_url:
350
- cdp_url = self._cdp_url_logic()
351
- browser = await p.chromium.connect_over_cdp(endpoint_url=cdp_url)
352
- else:
353
- browser = await p.chromium.launch(**self.__launch_kwargs())
354
-
355
- context = await browser.new_context(**self.__context_kwargs())
356
- page = await context.new_page()
357
- page.set_default_navigation_timeout(self.timeout)
358
- page.set_default_timeout(self.timeout)
359
- page.on("response", handle_response)
360
-
361
- if self.extra_headers:
362
- await page.set_extra_http_headers(self.extra_headers)
363
-
364
- if self.disable_resources:
365
- await page.route("**/*", async_intercept_route)
366
-
367
- if self.stealth:
368
- for script in self.__stealth_scripts():
369
- await page.add_init_script(path=script)
370
-
371
- first_response = await page.goto(url, referer=referer)
372
- await page.wait_for_load_state(state="domcontentloaded")
373
-
374
- if self.network_idle:
375
- await page.wait_for_load_state('networkidle')
376
-
377
- if self.page_action is not None:
378
- try:
379
- page = await self.page_action(page)
380
- except Exception as e:
381
- log.error(f"Error executing async page_action: {e}")
382
-
383
- if self.wait_selector and type(self.wait_selector) is str:
384
- try:
385
- waiter = page.locator(self.wait_selector)
386
- await waiter.first.wait_for(state=self.wait_selector_state)
387
- # Wait again after waiting for the selector, helpful with protections like Cloudflare
388
- await page.wait_for_load_state(state="load")
389
- await page.wait_for_load_state(state="domcontentloaded")
390
- if self.network_idle:
391
- await page.wait_for_load_state('networkidle')
392
- except Exception as e:
393
- log.error(f"Error waiting for selector {self.wait_selector}: {e}")
394
-
395
- # In case we didn't catch a document type somehow
396
- final_response = final_response if final_response else first_response
397
- if not final_response:
398
- raise ValueError("Failed to get a response from the page")
399
-
400
- # This will be parsed inside `Response`
401
- encoding = final_response.headers.get('content-type', '') or 'utf-8' # default encoding
402
- # PlayWright API sometimes give empty status text for some reason!
403
- status_text = final_response.status_text or StatusText.get(final_response.status)
404
-
405
- history = self._process_response_history(first_response)
406
- try:
407
- page_content = await page.content()
408
- except Exception as e:
409
- log.error(f"Error getting page content in async: {e}")
410
- page_content = ""
411
-
412
- response = Response(
413
- url=page.url,
414
- text=page_content,
415
- body=page_content.encode('utf-8'),
416
- status=final_response.status,
417
- reason=status_text,
418
- encoding=encoding,
419
- cookies={cookie['name']: cookie['value'] for cookie in await page.context.cookies()},
420
- headers=await first_response.all_headers(),
421
- request_headers=await first_response.request.all_headers(),
422
- history=history,
423
- **self.adaptor_arguments
424
- )
425
- await page.close()
426
- await context.close()
427
-
428
- return response
@@ -1,5 +0,0 @@
1
- // PDF viewer enabled
2
- // Bypasses `pdfIsDisabled` test in creepsjs's 'Like Headless' sections
3
- Object.defineProperty(navigator, 'pdfViewerEnabled', {
4
- get: () => true,
5
- });