| 17 | from subprocess import Popen, PIPE |
| 18 | |
| 19 | def get_configured_webdriver( |
| 20 | chrome_options_instance: Options = None, |
| 21 | driver_path: str = None, |
| 22 | base_service_args: list = None, |
| 23 | log_file_path: str = None, |
| 24 | additional_capabilities: dict = None, |
| 25 | port: int = None |
| 26 | ): |
| 27 | _port_arg_parser = argparse.ArgumentParser(prog='webdriver_setup_port_parser', add_help=False) |
| 28 | _port_arg_parser.add_argument( |
| 29 | "--chromedriver-port", |
| 30 | type=int, |
| 31 | default=None, |
| 32 | help="Port for Chromedriver. Overrides CHROMEDRIVER_PORT environment variable." |
| 33 | ) |
| 34 | _known_cli_args, _ = _port_arg_parser.parse_known_args() |
| 35 | |
| 36 | if port is not None: |
| 37 | _target_port = port |
| 38 | else: |
| 39 | _target_port = _known_cli_args.chromedriver_port |
| 40 | if _target_port is None: |
| 41 | env_port_str = os.environ.get('CHROMEDRIVER_PORT') |
| 42 | if env_port_str: |
| 43 | try: |
| 44 | _target_port = int(env_port_str) |
| 45 | except ValueError: |
| 46 | print(f"[WebDriver Setup] Warning: Invalid CHROMEDRIVER_PORT '{env_port_str}'. Letting Selenium pick.") |
| 47 | _target_port = None |
| 48 | |
| 49 | _final_service_args = list(base_service_args) if base_service_args else [] |
| 50 | |
| 51 | if _target_port: |
| 52 | _final_service_args.append(f"--port={_target_port}") |
| 53 | print(f"[WebDriver Setup] Using Chromedriver port: {_target_port}") |
| 54 | else: |
| 55 | _target_port = 0 |
| 56 | print(f"[WebDriver Setup] No specific port provided. Letting Selenium choose a free port.") |
| 57 | |
| 58 | if driver_path is None: |
| 59 | chromedriver_exe_path = os.environ.get('CHROMEDRIVER') |
| 60 | if not chromedriver_exe_path: |
| 61 | raise ValueError("[WebDriver Setup] Critical: CHROMEDRIVER environment variable is not set.") |
| 62 | else: |
| 63 | chromedriver_exe_path = driver_path |
| 64 | |
| 65 | _chrome_service = Service( |
| 66 | executable_path=chromedriver_exe_path, |
| 67 | port=_target_port, |
| 68 | service_args=_final_service_args if _final_service_args else None, |
| 69 | log_path=log_file_path, |
| 70 | ) |
| 71 | |
| 72 | if chrome_options_instance is None: |
| 73 | chrome_options_instance = Options() |
| 74 | chrome_options_instance.add_argument('--nwjs-test-mode2') |
| 75 | |
| 76 | if additional_capabilities and isinstance(additional_capabilities, dict): |