From 0bf986ee8b51afde8e894d4fe3838053ac3cb1c8 Mon Sep 17 00:00:00 2001 From: sebdelsol Date: Fri, 18 Mar 2022 15:41:53 +0100 Subject: [PATCH] fix corrupt prefs when the file already exists --- undetected_chromedriver/__init__.py | 1 + undetected_chromedriver/options.py | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/undetected_chromedriver/__init__.py b/undetected_chromedriver/__init__.py index cedae06..e8da4e6 100644 --- a/undetected_chromedriver/__init__.py +++ b/undetected_chromedriver/__init__.py @@ -375,6 +375,7 @@ class Chrome(selenium.webdriver.chrome.webdriver.WebDriver): config["profile"]["exit_type"] = None fs.seek(0, 0) json.dump(config, fs) + fs.truncate() # the file might be shorter logger.debug("fixed exit_type flag") except Exception as e: logger.debug("did not find a bad exit_type flag ") diff --git a/undetected_chromedriver/options.py b/undetected_chromedriver/options.py index f262319..79a8dd3 100644 --- a/undetected_chromedriver/options.py +++ b/undetected_chromedriver/options.py @@ -39,6 +39,20 @@ class ChromeOptions(_ChromiumOptions): value = ChromeOptions._undot_key(rest, value) return {key: value} + @staticmethod + def _merge_nested(a, b): + """ + merges b into a + leaf values in a are overwritten with values from b + """ + for key in b: + if key in a: + if isinstance(a[key], dict) and isinstance(b[key], dict): + ChromeOptions._merge_nested(a[key], b[key]) + continue + a[key] = b[key] + return a + def handle_prefs(self, user_data_dir): prefs = self.experimental_options.get("prefs") if prefs: @@ -55,7 +69,7 @@ class ChromeOptions(_ChromiumOptions): prefs_file = os.path.join(default_path, "Preferences") if os.path.exists(prefs_file): with open(prefs_file, encoding="latin1", mode="r") as f: - undot_prefs.update(json.load(f)) + undot_prefs = self._merge_nested(json.load(f), undot_prefs) with open(prefs_file, encoding="latin1", mode="w") as f: json.dump(undot_prefs, f)