如何制作 selenium 运行 'chrome.exe --remote-debugging-port=9222 --user-data-dir='C:\selenium\ChromeProfile'

how to make selenium run 'chrome.exe --remote-debugging-port=9222 --user-data-dir='C:\\selenium\\ChromeProfile'

我正在编写代码,让 selenium 接管 chrome 的一个实例,其中包含我所有的书签和内容。所以我创建了一个 chrome 配置文件并且我有命令

chrome.exe --remote-debugging-port=9222 --user-data-dir='C:\selenium\ChromeProfile'

当您在 python 终端中 运行 它时,此方法有效,但我不能只将其放入代码中。

我试过使用

import os

os.system("chrome.exe --remote-debugging-port=9222 --user-data-dir='C:\selenium\ChromeProfile'")

但是 returns 和

Failed To Create Data Directory: Google Chrome cannot read and write to its data directory: C\selenium\ChromeProfile

有人知道我做错了什么或将 运行 chrome 命令打开此特定配置文件的命令吗?

到目前为止我的总代码如下所示

import subprocess
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

os.system("chrome.exe --remote-debugging-port=9222 --user-data-dir='C:\selenium\ChromeProfile'")

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
chrome_driver = "C:\selenium\chromedriver.exe"
driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
#Print website title to make sure its connected properly
driver.get('https://google.com')
print(driver.title)

search_bar = driver.find_element_by_name('q')
search_bar.send_keys('test')

没关系的人,我想通了。我在这里发布这篇文章是为了将来可能 运行 遇到与你希望 python 在端口上以调试模式打开浏览器的相同问题的其他人。

这是代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


chrome_options = Options()
chrome_options.add_argument("--remote-debugging-port=9222")
chrome_options.add_argument('user-data-dir=C:\selenium\ChromeProfile')
chrome_driver = "C:\selenium\chromedriver.exe"
driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)

#Print website title to make sure its connected properly
driver.get('https://google.com')
print(driver.title)

search_bar = driver.find_element_by_name('q')
search_bar.send_keys('test')

我不得不添加两行

chrome_options.add_argument()

出于某种原因,我不喜欢将它们放在同一个括号中。 我希望我以后能帮助到别人。