utils-seleniumxp 1.0.0__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.
@@ -0,0 +1,965 @@
1
+ # Selenium webdriver utilities - XP version
2
+ # routines for starting / configuring browser sessions, currently full support for Chrome and Firefox only
3
+
4
+ """
5
+ Module with session handling functions
6
+
7
+ Session handling functions include:
8
+ - start a webdriver session with a new driver including logging
9
+ - connect a webdriver session to a running via debug port (Chrome only).
10
+ - browser setting bundling functions for a) direct download b) disabling notifications
11
+ c) optimized scraping
12
+
13
+ Currently full support is implemented for Chrome and Firefox only.
14
+ """
15
+
16
+
17
+ # ruff and mypy per file settings
18
+ #
19
+ # empty lines
20
+ # ruff: noqa: E302, E303
21
+ # naming conventions
22
+ # ruff: noqa: N801, N802, N803, N806, N812, N813, N815, N816, N818, N999
23
+ # boolean-type arguments
24
+ # ruff: noqa: FBT001, FBT002
25
+ # others
26
+ # ruff: noqa: B006, B008, B010, E501, PLC0415, PLR0914, PLR0917, PLR1702, PLR2004, RUF022, S101, S110, S113, SIM102
27
+ #
28
+ # disable mypy errors
29
+ # mypy: disable-error-code = "attr-defined, arg-type, call-overload, no-any-return, unused-ignore"
30
+
31
+ # fmt: off
32
+
33
+
34
+
35
+ # TODO Dev:
36
+ # - decorator to check brwoser type for various functions to simplify code ?
37
+ # - use user profiles ?
38
+ # - additional parameters in INI file Selenium.ini
39
+ # - implicitlywait
40
+ # - flag for stealth mode ?
41
+ # - flag for optimized scraping mode ?
42
+ # - combine with a wrapper for config
43
+ # https://github.com/MikeFez/BrowserWrapper/blob/main/BrowserWrapper/browserwrapper.py ?
44
+ # - include/activate webdriver management ?
45
+ # - Firefox improvements (but worth the effort as Chrome is faster anyway and currently causes problems?)
46
+ # - Firefox eventfiring webdriver: problem with hanging Firefox and hanging processes when checked last time
47
+ # - re-connect mechanism as for Chrome, seems to be supported from Selenium4 onwards
48
+ # feature calling seems to be similar to Chrome but it is unclear how to control marionette port (as the
49
+ # standard built-in Firefox automation driver) and Geckodriver supporting the Webdriver protocol
50
+ # for the Selenium side and if relevant
51
+ # -> advantage unclear, Chrome feature used to start browser session with VBA and hand it over
52
+ # but Firefox does not work with SeleniumBasic COM-wrapper anymore
53
+ # https://wiki.mozilla.org/Firefox/CommandLineOptions
54
+ # https://stackoverflow.com/questions/43272919/difference-between-webdriver-firefox-marionette-webdriver-gecko-driver
55
+ # https://stackoverflow.com/questions/57579761/is-there-any-way-to-change-the-webdrivers-port
56
+ # https://stackoverflow.com/questions/68340118/how-can-i-attach-firefoxdriver-to-a-running-instance-of-firefox
57
+ # https://stackoverflow.com/questions/72331816/how-to-connect-to-an-existing-firefox-instance-using-seleniumpython
58
+
59
+ # TODO Test:
60
+ # - n. a.
61
+
62
+
63
+
64
+ from typing import Any, Callable, Optional, Union
65
+
66
+ import os
67
+ # switch to pathlib postponed as os is required
68
+ # import pathlib
69
+ import tempfile
70
+ import configparser
71
+ import logging
72
+ import inspect
73
+ import atexit
74
+ import contextlib
75
+ import psutil
76
+ import signal
77
+
78
+ import requests
79
+
80
+ from stealthenium import stealth
81
+
82
+ import utils_seleniumxp.eventfiring_addon
83
+ import utils_mystuff as Utils
84
+
85
+
86
+
87
+ # block direct calling
88
+ # __all__ = []
89
+ __all__ = [
90
+ 'initWebDriver', 'init_webdriver',
91
+ 'directdownload',
92
+ 'disablenotifications',
93
+ 'connectChrome', 'connect_chrome',
94
+ 'checkDebugport', 'check_debugport'
95
+ ]
96
+
97
+
98
+
99
+ # supported browsers
100
+ supported_browsers = {"chrome": ("chrome.exe", "chromedriver.exe"), "firefox": ("firefox.exe", "geckodriver.exe")}
101
+
102
+ # switch stealth mode
103
+ stealthmode_default = False
104
+ # switch optimized scraping
105
+ optimizedscraping_default = False
106
+
107
+
108
+
109
+ # initialize selenium driver including starting new browser instance
110
+ def init_webdriver(
111
+ browser: Optional[str] = None,
112
+ inifile: Optional[str] = None,
113
+ inisection: str = "DEFAULT",
114
+ settings: list[Union[tuple[str], tuple[str, list[Any]]]] = [("disablenotifications",), ("directdownload", [tempfile.gettempdir()])],
115
+ debugport: int = 0,
116
+ implicitlywait: int = 10,
117
+ maxpageload: int = 30,
118
+ mixin: bool = utils_seleniumxp.mixinactive,
119
+ eventlistener: Optional[utils_seleniumxp.eventfiring_addon.AbstractEventListenerExtended] = None,
120
+ stealthmode: bool = stealthmode_default,
121
+ optimizedscraping: bool = optimizedscraping_default,
122
+ URL: str = "about:blank",
123
+ alt_cls_webdriverwrapper: Optional[type[utils_seleniumxp._RemoteWebDriver]] = None,
124
+ alt_cls_options: Union[type[utils_seleniumxp.WebDriver.ChromeOptions], type[utils_seleniumxp.WebDriver.FirefoxOptions], None] = None
125
+ ) -> utils_seleniumxp._RemoteWebDriver:
126
+ """
127
+ init_webdriver - initialize Selenium webdriver session
128
+
129
+ INI file:
130
+ The ini file provides a possibility to define profiles with extensions to be loaded and paths
131
+ to the webdriver binary and extension files. A profile section defines the browser, the driver path,
132
+ the extension path and the extensions to be loaded. Config file interpolation might be used for paths.
133
+ Per driver a driver specific section is required defining at least the file for the extensions.
134
+ Currently settings beyond paths and extensions are not supported.
135
+
136
+ settings:
137
+ settings is provided as a list of callables. The callables must return a browser-specific settings data object.
138
+ Refer to functions 'directdownload', 'disablenotifications' and 'optimizedscraping' as example.
139
+
140
+ alternative base class:
141
+ To use special bases like undetected_chromedriver it is possible to provide an alternative
142
+ browser class. Note that an alternative options class must be provided as well.
143
+
144
+ Args:
145
+ browser (Optional[str], optional): browser, read from INI file if not set. Defaults to None.
146
+ inifile (Optional[str], optional): INI file. Defaults to None.
147
+ inisection (str, optional): INI section to be evaluated. Defaults to "DEFAULT".
148
+ settings (list[Union[tuple[str], tuple[str, list[Any]]]], optional): Browser preference setting functions. Defaults to [("disablenotifications",), ("directdownload", [tempfile.gettempdir()])].
149
+ debugport (int, optional): set debugport (currently Chrome only). Defaults to 0.
150
+ implicitlywait (int, optional): implicit wait time. Defaults to 10.
151
+ maxpageload (int, optional): max pageload time. Defaults to 20.
152
+ mixin (bool, optional): flag to switch between mixin and setattr mode. Defaults to utils_seleniumxp.mixinactive.
153
+ eventlistener (Optional[utils_seleniumxp.eventfiring_addon.AbstractEventListenerExtended], optional): eventlistener object to activate eventfiring mode. Defaults to None.
154
+ stealthmode (bool, optional): flag to control selenium_stealth mode. Defaults to stealthmode_default.
155
+ optimizedscraping (bool, optional): flag to control optimized settings for scraping (no pictures etc.). Defaults to optimizedscraping_default.
156
+ URL (str, optional): start URL. Defaults to "about:blank".
157
+ alt_cls_webdriverwrapper (Optional[utils_seleniumxp.WebDriver], optional): optional base webdriver class. Defaults to None.
158
+ alt_cls_options (Union[utils_seleniumxp.WebDriver.ChromeOptions, utils_seleniumxp.WebDriver.FirefoxOptions, None], optional): optional browser options class. Defaults to None.
159
+
160
+ Returns:
161
+ utils_seleniumxp.WebDriver: webdriver object
162
+ """
163
+
164
+ # internal helper for session init routine
165
+
166
+ def evaluate_prefsfunction(prefsfunction: Any) -> Union[dict, list[tuple[str, Any]]]:
167
+
168
+ if type(prefsfunction) is tuple:
169
+ if len(prefsfunction) == 1:
170
+ prefsfunction = (prefsfunction[0], None)
171
+ else:
172
+ prefsfunction = (prefsfunction, None)
173
+ try:
174
+ if prefsfunction[1] is None:
175
+ return globals()[prefsfunction[0]](browser)
176
+ else:
177
+ return globals()[prefsfunction[0]](browser, *prefsfunction[1])
178
+ except Exception as exc_prefscfuntion_eval:
179
+ err_msg = f"Browser preference set {prefsfunction[0]} not defined."
180
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg) from exc_prefscfuntion_eval
181
+
182
+ def evaluate_extensionspath(evalfunc: Callable[[str], None], extensionspath: str) -> int:
183
+
184
+ extensions_installed = 0
185
+ if "extensions" in config[inisection]:
186
+ extensions = config[inisection]["extensions"].split(", ")
187
+ if len(extensions) > 0:
188
+ if sessionstartlog is not None:
189
+ sessionstartlog.info("Add-Ons:")
190
+ for extensionID in extensions:
191
+ # get-function used to enable fallback value
192
+ extensionfile = config[browser].get("extension_" + extensionID, fallback="") # type: ignore[index]
193
+ if extensionfile != "":
194
+ extensionfile = os.path.join(extensionspath, extensionfile)
195
+ # extensionfile = pathlib.Path(extensionspath).joinpath(extensionfile)
196
+ # if extensionfile.is_file():
197
+ if os.path.isfile(extensionfile):
198
+ evalfunc(extensionfile)
199
+ if sessionstartlog is not None:
200
+ sessionstartlog.info(f"- '{extensionfile}' for '{extensionID}' found.")
201
+ extensions_installed += + 1
202
+ elif sessionstartlog is not None:
203
+ sessionstartlog.info(f"- File '{extensionfile}' for '{extensionID}' not found.")
204
+ elif sessionstartlog is not None:
205
+ sessionstartlog.info(f"- Extensionfile for '{extensionID}' not defined.")
206
+ return extensions_installed
207
+
208
+ # start ini processing
209
+
210
+ regkey_AppPaths: str = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\"
211
+
212
+ # read config file (standard: seleniumpythonutils.ini)
213
+ config, config_without_default = read_configfile(inifile)
214
+
215
+ # activate sessionstart log
216
+ sessionstartlog = set_log_sessionstart(config, inisection)
217
+ if sessionstartlog is not None:
218
+ sessionstartlog.info("----- start webdriver session -----")
219
+ sessionstartlog.info("Parameters:")
220
+ # get arg-values without reference to callable
221
+ cframe = inspect.currentframe()
222
+ args_info = inspect.getargvalues(cframe)
223
+ # collecting args-values in a dictionary
224
+ argsdict = {arg: args_info.locals.get(arg) for arg in args_info.args}
225
+ # log args dictionary
226
+ for key, value in argsdict.items():
227
+ sessionstartlog.info(f"- {key}: {value}")
228
+
229
+ # read browser
230
+ if browser is None:
231
+ browser = config[inisection]["browser"]
232
+ # check browser
233
+ if browser not in supported_browsers:
234
+ err_msg = f"Browser '{browser}' not supported."
235
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
236
+
237
+ browserbinarypath: Optional[str] = None
238
+ driverpath: Optional[str] = None
239
+
240
+ # check binaries from config (Windows only)
241
+ if os.name == "nt":
242
+
243
+ # check browser binary location (for portable installations - only windows)
244
+ import winreg
245
+ browserbinary: str = supported_browsers[browser][0]
246
+ browserbinarypath = check_configpath(config, browser, "browserbinarypath", browserbinary, checkwd=False)
247
+ if browserbinarypath is None or browserbinarypath == "":
248
+ try:
249
+ winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, regkey_AppPaths + browserbinary)
250
+ except Exception as exc_winreg:
251
+ err_msg = f"Browser '{browser}' not installed and no portable app path provided."
252
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg) from exc_winreg
253
+
254
+ # use Selenium Manager as per default
255
+ # if not config.getboolean(browser, "use_seleniummanager"):
256
+ if not Utils.to_bool(config[browser]["use_seleniummanager"]):
257
+ # check/set webdriver executable path
258
+ driverbinary: str = supported_browsers[browser][1]
259
+ driverpath = check_configpath(config_without_default, inisection, "driverpath", driverbinary, checkwd=False)
260
+ if driverpath == "":
261
+ driverpath = check_configpath(config, browser, "driverpath", driverbinary, checkwd=True)
262
+ if driverpath == "":
263
+ driverpath = check_usrpath(config, browser, "usrpath_suffix_driver")
264
+ if driverpath is None or driverpath == "":
265
+ err_msg = f"Driver {driverbinary} for Browser '{browser}' could not be found in path defined in config file or current working directory."
266
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
267
+ else:
268
+ # set PATH
269
+ envpath = os.environ["PATH"]
270
+ if driverpath not in envpath:
271
+ os.environ["PATH"] += os.pathsep + driverpath
272
+
273
+ else:
274
+
275
+ # browserbinarypath = check_configpath(config, browser, "", "browserbinarypath", checkwd=False)
276
+ browserbinarypath = config[browser]["browserbinarypath"]
277
+
278
+ # optimized scraping (bot detection prevention)
279
+ if optimizedscraping and "optimizedscraping" not in settings:
280
+ settings.append(("optimizedscraping",))
281
+
282
+ # create browser options / profile object and set preferences
283
+ if browser == "chrome":
284
+
285
+ # set options object - some wrappers define own options class
286
+ browsersettings = utils_seleniumxp.WebDriver.ChromeOptions() if alt_cls_options is None else alt_cls_options()
287
+ assert isinstance(browsersettings, utils_seleniumxp.WebDriver.ChromeOptions)
288
+
289
+ # options / preferences
290
+ prefsdict: dict = {}
291
+ for prefsfunction in settings:
292
+ prefs = evaluate_prefsfunction(prefsfunction)
293
+ prefsdict = {**prefsdict, **prefs} # type: ignore[dict-item]
294
+ if len(prefsdict) > 0:
295
+ browsersettings.add_experimental_option("prefs", prefsdict)
296
+ if sessionstartlog is not None:
297
+ sessionstartlog.info("Preferences / Options:")
298
+ for key, value in prefsdict.items():
299
+ # log Chrome prefs
300
+ sessionstartlog.info(f"- {key}: {value}")
301
+
302
+ # settings for Chrome
303
+ browsersettings.add_argument("--disable-features=UserAgentClientHint,OptimizationGuideModelDownloading,OptimizationHintsFetching,OptimizationTargetPrediction,OptimizationHints")
304
+ browsersettings.add_argument("--disable-search-engine-choice-screen")
305
+ # settings in addition to stealth extension from stackoverflow
306
+ # https://stackoverflow.com/questions/53039551/selenium-webdriver-modifying-navigator-webdriver-flag-to-prevent-selenium-detec
307
+ # https://stackoverflow.com/questions/67341346/how-to-bypass-cloudflare-bot-protection-in-selenium
308
+ if stealthmode:
309
+ browsersettings.add_experimental_option("excludeSwitches", ["enable-automation"])
310
+ browsersettings.add_experimental_option("useAutomationExtension", False)
311
+ browsersettings.add_argument("--disable-blink-features=AutomationControlled")
312
+
313
+ # remote debugging (currently only Chrome)
314
+ if debugport != 0:
315
+ browsersettings.add_argument(f"--remote-debugging-port={debugport}")
316
+
317
+ elif browser == "firefox":
318
+
319
+ # set options object - some wrappers define own options class
320
+ browsersettings = utils_seleniumxp.WebDriver.FirefoxOptions() if alt_cls_options is None else alt_cls_options()
321
+ assert isinstance(browsersettings, utils_seleniumxp._RemoteWebDriver.FireFoxOptions)
322
+
323
+ # options / preferences
324
+ if len(settings) > 0:
325
+ if sessionstartlog is not None:
326
+ sessionstartlog.info("Preferences / Options:")
327
+ for prefsfunction in settings:
328
+ prefs = evaluate_prefsfunction(prefsfunction)
329
+ for pref in prefs:
330
+ browsersettings.set_preference(pref[0], pref[1])
331
+ # log FireFox prefs
332
+ if sessionstartlog is not None:
333
+ sessionstartlog.info(f"- {pref[0]}: {pref[1]}")
334
+
335
+ # does not work anymore with Selenium 4.x
336
+ # browsersettings.set_preference("xpinstall.signatures.required", False) # for unsigned extensions
337
+
338
+ # potentially switch to options.profile to be amended (Selenium 4)
339
+
340
+ # settings for Firefox
341
+ # settings in addition to stealth extension from stackoverflow (currently Chrome only)
342
+ if stealthmode:
343
+ pass
344
+
345
+ # remote debugging (currently Chrome only)
346
+ if debugport != 0:
347
+ pass
348
+
349
+ # set browser binary location in webdriver/browser profile
350
+ if browserbinarypath is not None:
351
+ browsersettings.binary_location = os.path.join(browserbinarypath, browserbinary)
352
+
353
+ # install requested extensions
354
+ # Selenium 3.x: not working properly with FireFox but no error message
355
+ # Selenium 4.x: sub-routine evaluate as Chrome includes add-on in options but firefox requires webdriver start first
356
+ extensionspath = check_configpath(config_without_default, inisection, "extensionspath")
357
+ if extensionspath == "":
358
+ extensionspath = check_configpath(config, browser, "extensionspath")
359
+ if extensionspath == "":
360
+ extensionspath = check_usrpath(config, browser, "usrpath_suffix_ext")
361
+ if extensionspath == "":
362
+ err_msg = f"Extensions for Browser '{browser}' could not be found in path defined in config file."
363
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
364
+
365
+ # install requested extensions - Chrome
366
+ if browser == "chrome" and extensionspath != "":
367
+
368
+ assert isinstance(browsersettings, utils_seleniumxp.WebDriver.ChromeOptions)
369
+ extensions_installed = evaluate_extensionspath(
370
+ browsersettings.add_extension, extensionspath
371
+ )
372
+ # fix according to https://github.com/SeleniumHQ/selenium/issues/15788
373
+ if extensions_installed > 0:
374
+ browsersettings.add_argument("--disable-features=DisableLoadExtensionCommandLineSwitch")
375
+
376
+ # instantiate Selenium webdriver + browser, load blank page
377
+ if browser == "chrome":
378
+ cls_webdriver = utils_seleniumxp.WebDriver.Chrome
379
+ if alt_cls_webdriverwrapper is not None:
380
+ if (browser.upper() in [mro_cls.__module__.upper() for mro_cls in alt_cls_webdriverwrapper.__mro__]) or \
381
+ ("selenium.webdriver.chrome.webdriver" in [mro_cls.__module__ for mro_cls in alt_cls_webdriverwrapper.__mro__]):
382
+ cls_webdriver = alt_cls_webdriverwrapper # type: ignore[assignment]
383
+ elif browser == "firefox":
384
+ cls_webdriver = utils_seleniumxp.WebDriver.Firefox # type: ignore[assignment]
385
+ if alt_cls_webdriverwrapper is not None:
386
+ if (browser.upper() in [mro_cls.__module__.upper() for mro_cls in alt_cls_webdriverwrapper.__mro__]) or \
387
+ ("selenium.webdriver.firefox.webdriver" in [mro_cls.__module__ for mro_cls in alt_cls_webdriverwrapper.__mro__]):
388
+ cls_webdriver = alt_cls_webdriverwrapper # type: ignore[assignment]
389
+ if mixin or utils_seleniumxp.mixinactive:
390
+ webdriver = utils_seleniumxp.webdriver_addon.WebDriverMixedin(cls_webdriver)(options=browsersettings)
391
+ else:
392
+ webdriver = utils_seleniumxp.webdriver_addon.WebDriverMixedinOnly3rdParty(cls_webdriver)(options=browsersettings)
393
+ if eventlistener is not None:
394
+ if mixin or utils_seleniumxp.mixinactive:
395
+ webdriver = utils_seleniumxp.webdriver_addon.EventFiringWebDriverExtendedMixedin(webdriver, eventlistener) # type: ignore[assignment]
396
+ else:
397
+ webdriver = utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended(webdriver, eventlistener) # type: ignore[assignment]
398
+ webdriver.get("about:blank")
399
+
400
+ # install requested extensions - Firefox
401
+ if browser == "firefox" and extensionspath != "":
402
+ extensions_installed = evaluate_extensionspath(
403
+ webdriver.install_addon, extensionspath
404
+ )
405
+
406
+ # set implicitly wait if defined
407
+ if implicitlywait != 0:
408
+ webdriver.implicitly_wait(implicitlywait)
409
+
410
+ # set maxpage load
411
+ if maxpageload != 0:
412
+ webdriver.set_page_load_timeout(maxpageload)
413
+
414
+ # close browser windows from extensions
415
+ if extensions_installed > 0:
416
+ webdriver.wait4HTMLstable()
417
+ if len(webdriver.window_handles) > 1:
418
+ while len(webdriver.window_handles) > 1:
419
+ webdriver.close()
420
+
421
+ # activate stealth mode (so far only available for chrome)
422
+ if stealthmode:
423
+ # set full screen-size as anti-bot measure -> would require screen-size not to be changed by calling programm
424
+ webdriver.maximize_window()
425
+ # delete navigator flag
426
+ webdriver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => false})")
427
+ # browser-specific stuff
428
+ if browser == "chrome":
429
+ webdriver.execute_cdp_cmd(
430
+ "Page.addScriptToEvaluateOnNewDocument",
431
+ {
432
+ "source": """
433
+ Object.defineProperty(navigator, 'webdriver', {get: () => undefined})
434
+ """
435
+ }
436
+ )
437
+ # solve wrapping issue for EventFiringWebDriver
438
+ webdriver_temp = webdriver.wrapped_driver if hasattr(webdriver, "wrapped_driver") else webdriver
439
+ stealth(
440
+ driver=webdriver_temp,
441
+ user_agent="",
442
+ languages=["en-US", "en", "de-DE", "de"],
443
+ vendor="Google Inc.",
444
+ platform="Win32",
445
+ webgl_vendor="Intel Inc.",
446
+ renderer="Intel Iris OpenGL Engine",
447
+ fix_hairline=True,
448
+ run_on_insecure_origins=False
449
+ )
450
+
451
+ # get URL
452
+ if URL != "about:blank":
453
+ webdriver.get(URL)
454
+
455
+ # close log for session start
456
+ close_log_sessionstart(sessionstartlog)
457
+
458
+ # set logging for closing popups
459
+ set_log_closepopup(webdriver, config, inisection)
460
+
461
+ # make sure closepopup log is closed when application ends
462
+ atexit.register(close_log_closepopup, webdriver)
463
+ # make sure webdriver process is killed when application ends
464
+ atexit.register(kill_driver_processes, browser, webdriver.service.process.pid)
465
+
466
+ return webdriver
467
+
468
+ def initWebDriver(
469
+ browser: Optional[str] = None,
470
+ inifile: Optional[str] = None,
471
+ inisection: str = "DEFAULT",
472
+ settings: list[Union[tuple[str], tuple[str, list[Any]]]] = [("disablenotifications",), ("directdownload", [tempfile.gettempdir()])],
473
+ debugport: int = 0,
474
+ implicitlywait: int = 10,
475
+ maxpageload: int = 30,
476
+ mixin: bool = utils_seleniumxp.mixinactive,
477
+ eventlistener: Optional[utils_seleniumxp.eventfiring_addon.AbstractEventListenerExtended] = None,
478
+ stealthmode: bool = stealthmode_default,
479
+ optimizedscraping: bool = optimizedscraping_default,
480
+ URL: str = "about:blank",
481
+ alt_cls_webdriverwrapper: Optional[utils_seleniumxp._RemoteWebDriver] = None,
482
+ alt_cls_options: Union[utils_seleniumxp.WebDriver.ChromeOptions, utils_seleniumxp.WebDriver.FirefoxOptions, None] = None
483
+ ) -> utils_seleniumxp._RemoteWebDriver:
484
+ """
485
+ initWebDriver - initialize Selenium webdriver session
486
+
487
+ INI file:
488
+ The ini file provides a possibility to define profiles with extensions to be loaded and paths
489
+ to the webdriver binary and extension files. A profile section defines the browser, the driver path,
490
+ the extension path and the extensions to be loaded. Config file interpolation might be used for paths.
491
+ Per driver a driver specific section is required defining at least the file for the extensions.
492
+ Currently settings beyond paths and extensions are not supported.
493
+
494
+ settings:
495
+ settings is provided as a list of callables. The callables must return a browser-specific settings data object.
496
+ Refer to functions 'directdownload', 'disablenotifications' and 'optimizedscraping' as example.
497
+
498
+ alternative base class:
499
+ To use special bases like undetected_chromedriver it is possible to provide an alternative
500
+ browser class. Note that an alternative options class must be provided as well.
501
+
502
+ Args:
503
+ browser (Optional[str], optional): browser, read from INI file if not set. Defaults to None.
504
+ inifile (Optional[str], optional): INI file. Defaults to None.
505
+ inisection (str, optional): INI section to be evaluated. Defaults to "DEFAULT".
506
+ settings (list[Union[tuple[str], tuple[str, list[Any]]]], optional): Browser preference setting functions. Defaults to [("disablenotifications",), ("directdownload", [tempfile.gettempdir()])].
507
+ debugport (int, optional): set debugport (currently Chrome only). Defaults to 0.
508
+ implicitlywait (int, optional): implicit wait time. Defaults to 10.
509
+ maxpageload (int, optional): max pageload time. Defaults to 20.
510
+ mixin (bool, optional): flag to switch between mixin and setattr mode. Defaults to utils_seleniumxp.mixinactive.
511
+ eventlistener (Optional[utils_seleniumxp.eventfiring_addon.AbstractEventListenerExtended], optional): eventlistener object to activate eventfiring mode. Defaults to None.
512
+ stealthmode (bool, optional): flag to control selenium_stealth mode. Defaults to stealthmode_default.
513
+ optimizedscraping (bool, optional): flag to control optimized settings for scraping (no pictures etc.). Defaults to optimizedscraping_default.
514
+ URL (str, optional): start URL. Defaults to "about:blank".
515
+ alt_cls_webdriverwrapper (Optional[utils_seleniumxp.WebDriver], optional): optional base webdriver class. Defaults to None.
516
+ alt_cls_options (Union[utils_seleniumxp.WebDriver.ChromeOptions, utils_seleniumxp.WebDriver.FirefoxOptions, None], optional): optional browser options class. Defaults to None.
517
+
518
+ Returns:
519
+ utils_seleniumxp.WebDriver: webdriver object
520
+ """
521
+ return init_webdriver(
522
+ browser, inifile, inisection, settings, debugport,
523
+ implicitlywait, maxpageload, mixin, eventlistener,
524
+ stealthmode, optimizedscraping, URL,
525
+ alt_cls_webdriverwrapper, alt_cls_options
526
+ )
527
+
528
+
529
+ # initialize selenium driver - check existing Chrome browser instance before connecting
530
+ def check_debugport(debugport: int) -> bool:
531
+ """
532
+ check_debugport - check port if activated as debugport
533
+
534
+ Args:
535
+ debugport (int): port number
536
+
537
+ Returns:
538
+ bool: flag if port connects to a browser
539
+ """
540
+
541
+ checkDbgPortOK = False
542
+ try:
543
+ response = requests.get("http://localhost:" + str(debugport))
544
+ except Exception:
545
+ return False
546
+
547
+ checkDbgPortOK = ((response.status_code == 200) and (response.reason == "OK"))
548
+
549
+ return checkDbgPortOK
550
+
551
+ def checkDebugport(debugport: int) -> bool:
552
+ """
553
+ checkDebugport - check port if activated as debugport
554
+
555
+ Args:
556
+ debugport (int): port number
557
+
558
+ Returns:
559
+ bool: flag if port connects to a browser
560
+ """
561
+ return check_debugport(debugport)
562
+
563
+
564
+ # initialize selenium driver - connect to existing Chrome browser instance
565
+ # https://cosmocode.io/how-to-connect-selenium-to-an-existing-browser-that-was-opened-manually/
566
+ def connect_chrome(
567
+ debugport: int,
568
+ inifile: Optional[str] = None,
569
+ inisection: str = "DEFAULT",
570
+ mixin: bool = utils_seleniumxp.mixinactive,
571
+ eventlistener: Optional[utils_seleniumxp.AbstractEventListener] = None,
572
+ URL: str = "about:blank"
573
+ ) -> Optional[utils_seleniumxp._RemoteWebDriver]:
574
+ """
575
+ connect_chrome - connect to Chrome instance via debugport
576
+
577
+ Args:
578
+ debugport (int): assumed debug port of Chrome instance
579
+ inifile (Optional[str], optional): INI file. Defaults to None.
580
+ inisection (str, optional): INI section to be evaluated. Defaults to "DEFAULT".
581
+ mixin (bool, optional): flag to switch between mixin and setattr mode. Defaults to utils_seleniumxp.mixinactive.
582
+ eventlistener (Optional[utils_seleniumxp.eventfiring_addon.AbstractEventListenerExtended], optional): eventlistener object to activate eventfiring mode. Defaults to None.
583
+ URL (str, optional): start URL. Defaults to "about:blank".
584
+
585
+ Returns:
586
+ utils_seleniumxp.WebDriver: webdriver object
587
+ """
588
+
589
+ # check if debugport active with browser instance
590
+ if not check_debugport(debugport):
591
+ return None
592
+
593
+ browser = "chrome"
594
+
595
+ # read config file (standard: selenium.ini)
596
+ config, config_without_default = read_configfile(inifile)
597
+
598
+ driverpath: Optional[str] = None
599
+
600
+ # check binaries from config (Windows only)
601
+ if os.name == "nt":
602
+
603
+ # use Selenium Manager as per default
604
+ # if not config.getboolean(browser, "use_seleniummanager"):
605
+ if not Utils.to_bool(config[browser]["use_seleniummanager"]):
606
+ # check/set webdriver executable path
607
+ driverbinary: str = supported_browsers[browser][1]
608
+ driverpath = check_configpath(config_without_default, inisection, "driverpath", driverbinary, checkwd=False)
609
+ if driverpath == "":
610
+ driverpath = check_configpath(config, browser, "driverpath", driverbinary, checkwd=True)
611
+ if driverpath == "":
612
+ driverpath = check_usrpath(config, browser, "usrpath_suffix_driver")
613
+ if driverpath == "":
614
+ err_msg = f"Driver {driverbinary} for Browser '{browser}' could not be found in path defined in config file or current working directory."
615
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
616
+ else:
617
+ # set PATH
618
+ envpath = os.environ["PATH"]
619
+ if driverpath not in envpath: # type: ignore[operator]
620
+ os.environ["PATH"] += os.pathsep + driverpath # type: ignore[operator]
621
+
622
+ # create browser options / profile object and set preferences
623
+ browsersettings = utils_seleniumxp.WebDriver.ChromeOptions()
624
+ # connect to existing browser instance via debug-port (chrome only)
625
+ browsersettings.add_experimental_option("debuggerAddress", f"localhost:{debugport}")
626
+
627
+ # instantiate Selenium webdriver, load blank page
628
+ if mixin or utils_seleniumxp.mixinactive:
629
+ webdriver = utils_seleniumxp.webdriver_addon.WebDriverMixedin(utils_seleniumxp.WebDriver.Chrome)(
630
+ options=browsersettings
631
+ )
632
+ else:
633
+ webdriver = utils_seleniumxp.webdriver_addon.WebDriverMixedinOnly3rdParty(utils_seleniumxp.WebDriver.Chrome)(
634
+ options=browsersettings
635
+ )
636
+ if eventlistener is not None:
637
+ if mixin or utils_seleniumxp.mixinactive:
638
+ webdriver = utils_seleniumxp.eventfiring_addon.EventFiringWebDriverExtended(webdriver, eventlistener) # type: ignore[assignment]
639
+ else:
640
+ webdriver = utils_seleniumxp.webdriver_addon.EventFiringWebDriverExtendedMixedin(webdriver, eventlistener) # type: ignore[assignment]
641
+ # webdriver.get("about:blank")
642
+
643
+ # set logging for closepopup
644
+ set_log_closepopup(webdriver, config, inisection)
645
+
646
+ # get URL
647
+ if URL != "about:blank":
648
+ webdriver.get(URL)
649
+
650
+ # make sure closepopup log is closed when application ends
651
+ atexit.register(close_log_closepopup, webdriver)
652
+ # make sure webdriver process(es) is/are killed when application ends
653
+ # -> does not need to happen as chromedriver.exe of calling application might be killed?
654
+ # atexit.register(os.kill, webdriver.service.process.pid, signal.SIGTERM)
655
+ atexit.register(kill_driver_processes, browser, webdriver.service.process.pid)
656
+
657
+ return webdriver
658
+
659
+ def connectChrome(
660
+ debugport: int,
661
+ inifile: Optional[str] = None,
662
+ inisection: str = "DEFAULT",
663
+ mixin: bool = utils_seleniumxp.mixinactive,
664
+ eventlistener: Optional[utils_seleniumxp.AbstractEventListener] = None,
665
+ URL: str = "about:blank"
666
+ ) -> Optional[utils_seleniumxp._RemoteWebDriver]:
667
+ """
668
+ connectChrome - connect to Chrome instance via debugport
669
+
670
+ Args:
671
+ debugport (int): assumed debug port of Chrome instance
672
+ inifile (Optional[str], optional): INI file. Defaults to None.
673
+ inisection (str, optional): INI section to be evaluated. Defaults to "DEFAULT".
674
+ mixin (bool, optional): flag to switch between mixin and setattr mode. Defaults to utils_seleniumxp.mixinactive.
675
+ eventlistener (Optional[utils_seleniumxp.eventfiring_addon.AbstractEventListenerExtended], optional): eventlistener object to activate eventfiring mode. Defaults to None.
676
+ URL (str, optional): start URL. Defaults to "about:blank".
677
+
678
+ Returns:
679
+ utils_seleniumxp.WebDriver: webdriver object
680
+ """
681
+ return connect_chrome(debugport, inifile, inisection, mixin, eventlistener, URL)
682
+
683
+
684
+
685
+ # utilities for initialization
686
+
687
+ # read config file
688
+ def read_configfile(inifile: Optional[str]) -> tuple[configparser.ConfigParser, configparser.ConfigParser]:
689
+ """
690
+ read_configfile - read config file
691
+
692
+ Args:
693
+ inifile (Optional[str], optional): INI file with config data. Defaults to None.
694
+
695
+ Returns:
696
+ configparser.ConfigParser: configparser object
697
+ """
698
+
699
+ if inifile is None or not os.path.isfile(inifile):
700
+ inifile = os.path.join(os.path.expanduser("~"), "SeleniumPythonUtils.ini")
701
+ if not os.path.isfile(inifile):
702
+ inifile = os.path.join(os.path.dirname(__file__), "SeleniumPythonUtils.ini")
703
+
704
+ config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
705
+ config.read(inifile)
706
+
707
+ config_without_default = configparser.ConfigParser(default_section=None, interpolation=configparser.ExtendedInterpolation())
708
+ config_without_default.read(inifile)
709
+
710
+ return config, config_without_default
711
+
712
+ # check path parameter from config
713
+ # used to check
714
+ # - browser binary location (for portable installations)
715
+ # - webdriver location
716
+ def check_configpath(
717
+ config: configparser.ConfigParser,
718
+ inisection: str,
719
+ configparampath: str,
720
+ binaryfile: str = "",
721
+ checkwd: bool = False
722
+ ) -> Optional[str]:
723
+ """
724
+ check_configpath - check path for binaries
725
+ """
726
+
727
+ checkpath: str = config.get(inisection, configparampath, fallback="")
728
+
729
+ if checkpath != "":
730
+ checkpath = os.path.expandvars(checkpath)
731
+ if binaryfile:
732
+ if os.path.isdir(checkpath):
733
+ if os.path.isfile(os.path.join(checkpath, binaryfile)):
734
+ return checkpath
735
+ if checkwd:
736
+ checkpath = os.getcwd()
737
+ if os.path.isfile(os.path.join(checkpath, binaryfile)):
738
+ return checkpath
739
+ elif os.path.isdir(checkpath):
740
+ return checkpath
741
+
742
+ return ""
743
+
744
+ # check path parameter from config
745
+ # used to check fallback via userprofile
746
+ def check_usrpath(config: configparser.ConfigParser, inisection: str, configparampathsuffix: str) -> Optional[str]:
747
+ """
748
+ check_usrpath - check path für user path suffix from config file
749
+ """
750
+
751
+ homepath = os.path.expanduser("~")
752
+ try:
753
+ checkpath = os.path.join(homepath, os.path.expandvars(config[inisection][configparampathsuffix]))
754
+ if os.path.isdir(checkpath):
755
+ return checkpath
756
+ except Exception:
757
+ pass
758
+
759
+ return ""
760
+
761
+
762
+ # predefined config-setting packages (only for new browser instances)
763
+
764
+ # config/options-settings for direct download - Chrome & Firefox
765
+ # routine to be used as function parameter for Selenium webdriver initialization/generator function
766
+ def directdownload(browser: str, defaultdir: Optional[str]) -> Union[dict, list, None]:
767
+ """
768
+ directdownload - create settings data object with config/options-settings for direct download
769
+
770
+ Args:
771
+ browser (str): browser
772
+ defaultdir (str, optional): target directory. Defaults to None.
773
+
774
+ Returns:
775
+ Union[dict, list, None]: settings data object
776
+ """
777
+
778
+ if browser not in supported_browsers:
779
+ err_msg = f"Browser '{browser}' not supported."
780
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
781
+
782
+ if defaultdir is None:
783
+ defaultdir = tempfile.gettempdir()
784
+
785
+ if browser == "chrome":
786
+ return {
787
+ "download.default_directory": defaultdir,
788
+ "download.prompt_for_download": False,
789
+ "plugins.always_open_pdf_externally": True
790
+ }
791
+ elif browser == "firefox":
792
+ return [
793
+ ("browser.download.folderList", 2),
794
+ ("browser.download.dir", defaultdir),
795
+ ("browser.download.manager.showWhenStarting", False),
796
+ ("browser.helperApps.alwaysAsk.force", False),
797
+ ("browser.helperApps.neverAsk.saveToDisk", "application/pdf,text/csv"),
798
+ ("pdfjs.disabled", True)
799
+ ]
800
+ return None
801
+
802
+ # config/options-settings for disabling notifications - Chrome & Firefox
803
+ # routine to be used as function parameter for Selenium webdriver initialization/generator function
804
+ def disablenotifications(browser: str) -> Union[dict, list, None]:
805
+ """
806
+ disablenotifications - create settings data object with config/options-settings for disabling notifications
807
+
808
+ Args:
809
+ browser (str): browser
810
+
811
+ Returns:
812
+ Union[dict, list, None]: settings data object
813
+ """
814
+
815
+ if browser not in supported_browsers:
816
+ err_msg = f"Browser '{browser}' not supported."
817
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
818
+
819
+ if browser == "chrome":
820
+ return {
821
+ "profile.managed_default_content_settings.notifications": 2
822
+ }
823
+ elif browser == "firefox":
824
+ return [
825
+ ("dom.webnotifications.enabled", False),
826
+ ]
827
+ return None
828
+
829
+ # config/options-settings for optimized scraping - Chrome & Firefox
830
+ # routine to be used as function parameter for Selenium webdriver initialization/generator function
831
+ #
832
+ # inspiration:
833
+ # https://github.com/dinuduke/Selenium-chrome-firefox-tips
834
+ # https://petertc.medium.com/pro-tips-for-selenium-setup-1855a11f88f8
835
+ # 0 -> default, 1 -> allow, 2 -> block
836
+ # NOTE: cookies must be allowed to click popup "away"
837
+ def optimizedscraping(browser: str) -> Union[dict, list, None]:
838
+ """
839
+ optimizedscraping - create settings data object with config/options-settings for optimized scraping
840
+
841
+ Args:
842
+ browser (str): browser
843
+
844
+ Returns:
845
+ Union[dict, list, None]: settings data object
846
+ """
847
+
848
+ if browser not in supported_browsers:
849
+ err_msg = f"Browser '{browser}' not supported."
850
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
851
+
852
+ if browser == "chrome":
853
+ return {
854
+ "profile.default_content_setting_values.notifications": 2,
855
+ "profile.managed_default_content_settings.images": 2,
856
+ "profile.managed_default_content_settings.stylesheets": 2,
857
+ "profile.managed_default_content_settings.cookies": 1,
858
+ "profile.managed_default_content_settings.javascript": 1,
859
+ "profile.managed_default_content_settings.plugins": 1,
860
+ "profile.managed_default_content_settings.popups": 2,
861
+ "profile.managed_default_content_settings.geolocation": 2,
862
+ "profile.managed_default_content_settings.media_stream": 2
863
+ }
864
+ elif browser == "firefox":
865
+ return [
866
+ ("permissions.default.stylesheet", 2),
867
+ ("permissions.default.image", 2),
868
+ ("dom.ipc.plugins.enabled.libflashplayer.so", "false")
869
+ ]
870
+ return None
871
+
872
+
873
+ # routines to support other stuff - routines not used as direct callables for mixin-methods or any kind of wrapping
874
+
875
+ # set up log for session initialization
876
+
877
+ def set_log_sessionstart(config: configparser.ConfigParser, inisection: str) -> Optional[logging.Logger]:
878
+ """
879
+ set_log_sessionstart - initialize logger for logging of session start
880
+
881
+ Args:
882
+ config (configparser.ConfigParser): configuration parser object filed form INI file
883
+ inisection (str): INI file section
884
+
885
+ Returns:
886
+ Optional[logging.Logger]: logger object
887
+ """
888
+
889
+ # if config[inisection]["log_sessionstart"]:
890
+ if config.getboolean(inisection, "log_sessionstart"):
891
+ logpath = config.get(inisection, "log_sessionstart_path")
892
+ return Utils.initLogger(loggername="Log_SessionStart", filename=logpath)
893
+ else:
894
+ return None
895
+
896
+ def close_log_sessionstart(sessionstart_logger: Optional[logging.Logger]) -> None:
897
+ """
898
+ close_log_sessionstart - close logger for logging session start
899
+
900
+ Args:
901
+ sessionstart_logger (Optional[logging.Logger]): logger
902
+ """
903
+
904
+ if sessionstart_logger is not None:
905
+ for handler in sessionstart_logger.handlers:
906
+ handler.close()
907
+
908
+ # set up log for closepopup
909
+
910
+ def set_log_closepopup(webdriver: utils_seleniumxp._RemoteWebDriver, config: configparser.ConfigParser, inisection: str) -> None:
911
+ """
912
+ set_log_closepopup - initialize logger for logging close popups
913
+
914
+ Args:
915
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver object
916
+ config (configparser.ConfigParser): configuration parser object filed form INI file
917
+ inisection (str): INI file section
918
+ """
919
+
920
+ # if config[inisection]["log_closepopup"]:
921
+ if config.getboolean(inisection, "log_closepopup"):
922
+ logpath = config.get(inisection, "log_closepopup_path")
923
+ setattr(webdriver, "closepopup_logger", Utils.initLogger(loggername="Log_ClosePopup", filename=logpath))
924
+
925
+ def close_log_closepopup(webdriver: utils_seleniumxp._RemoteWebDriver) -> None:
926
+ """
927
+ close_log_closepopup - close logger for logging close popups
928
+
929
+ Args:
930
+ webdriver (utils_seleniumxp._RemoteWebDriver): webdriver object
931
+ """
932
+
933
+ if hasattr(webdriver, "closepopup_logger"):
934
+ if webdriver.closepopup_logger is not None:
935
+ for handler in webdriver.closepopup_logger.handlers:
936
+ handler.close()
937
+
938
+
939
+ # clean up driver processes
940
+ def kill_driver_processes(browser: str = "chrome", pid: Optional[int] = None) -> None:
941
+ """
942
+ kill_driver_processes - routine to kill driver process(es) for automated clean-up
943
+
944
+ Args:
945
+ browser (str, optional): browser. Defaults to "chrome".
946
+ pid (Optional[int], optional): process ID
947
+ """
948
+
949
+ if browser not in supported_browsers:
950
+ err_msg = f"Browser '{browser}' not supported."
951
+ raise utils_seleniumxp.ErrorUtilsSelenium(err_msg)
952
+
953
+ driverbinary: str = supported_browsers[browser][1]
954
+ with contextlib.suppress(psutil.NoSuchProcess):
955
+ psutil.Process(pid).send_signal(signal.SIGTERM)
956
+ pids: list[int] = []
957
+ try:
958
+ for proc in psutil.process_iter(["name"]):
959
+ if proc.info["name"] == driverbinary:
960
+ if pid is None or pid == proc.pid:
961
+ pids.append(proc.pid)
962
+ except Exception:
963
+ pass
964
+ for pid in pids: # noqa: PLR1704
965
+ psutil.Process(pid).send_signal(signal.SIGTERM)