Python 使用用户数据目录参数启动chromedriver时WebDriverException

Python 使用用户数据目录参数启动chromedriver时WebDriverException,python,selenium-chromedriver,Python,Selenium Chromedriver,我的代码: from selenium.webdriver.chrome.options import Options from selenium import webdriver opts = Options() opts.add_argument("user-data-dir=/path/to/profiles_dir/user_id") browser = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver", chrome_o

我的代码:

from selenium.webdriver.chrome.options import Options
from selenium import webdriver
opts = Options()
opts.add_argument("user-data-dir=/path/to/profiles_dir/user_id")
browser = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver", chrome_options=opts)
当我为id=1的用户启动Chromium时,它会正常启动,并创建一个概要文件目录/path/to/profiles\u dir/1。 然后我访问一些任意站点并关闭浏览器。 当我第二次执行上述代码时,它会抛出异常

selenium.common.exceptions.WebDriverException:消息:未知错误:无法解析内部JSON模板:行:1,列:1,意外标记。 (驱动程序信息:chromedriver=2.35.528139(47ead77cb35ad2a9a83248b292151462a66cd881),平台=Linux 4.4.0-112-generic x86_64)

  • Chromium 64.0.3282.119构建在Ubuntu上,运行在Ubuntu 16.04上

  • 铬驱动2.35

  • 硒3.8.1


我在谷歌上搜索了很多,但找不到解决这个问题的方法。为什么我不能用现有的用户配置文件目录加载浏览器?我做错了什么?

chromedriver中似乎有一个bug。我缩小了范围,两个文件似乎是罪魁祸首:
{user data dir}/Local State
{user data dir}/{profile directory}/Preferences
。 如果未指定
配置文件目录
,则该目录将为“默认”

Chrome/Chrome似乎无法读取这些文件,即使您使用
browser.quit()
正确关闭chromedriver

您需要删除这些文件,以便能够使用相同的配置文件再次启动chromedriver

为了删除文件,我在我的
finally
块中使用了以下代码:

if browser is not None:
    browser.quit()
    time.sleep(1)
delete_paths = ['../selenium/chrome_profile/Local State',
                '../selenium/chrome_profile/Default/Preferences']
for delete_path in delete_paths:
    if os.path.exists(delete_path):
        os.remove(delete_path)

我的用户数据目录路径包含一个“相对”部分,例如/path/to/My/dir/。/../chromiu profiles似乎将其替换为直接路径,例如/path/to/chromiu profiles修复了错误。虽然我仍然不明白为什么它可以创建一个profile dir,但是以后无法读取它。在这之后,我遇到了一个新错误:ConnectionResetError:[Errno 104]由对等方重置连接。这是通过将Selenium降级到3.8.0修复的。您能够重现错误吗?关闭浏览器是否总是导致Chrome在下次启动时无法读取配置文件?是的,除非我删除上述文件,否则Chrome在下次启动时无法读取配置文件。我可以在最新的ChromeDriver 2.37中重现该错误。根据我的经验,问题在于
首选项
文件为空-因此出现了错误。因此,解决方案是检查这些文件是否包含内容。并且该内容必须是有效的JSON。基本上,Chrome无法读取它。在我的情况下,这是由于服务器崩溃