Selenium Chrome 附加默认配置文件

0 投票
2 回答
5467 浏览
提问于 2025-04-17 18:16

我正在使用Python和Selenium来自动化一些流程,但无法将Selenium连接到默认的Chrome用户配置文件。

capability = webdriver.DesiredCapabilities.CHROME
self.driver = webdriver.Remote('http://127.0.0.1:9515/wd/hib',capability)

当然,我是先启动了chromedriver,然后也尝试了,

import time
from selenium import webdriver
import selenium.webdriver.chrome.service as service
service = service.Service('./chromedriver')
service.start()
capabilities = {'chrome.binary': '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'}
driver = webdriver.Remote(service.service_url, capabilities)
driver.get('http://www.google.com/xhtml');
time.sleep(5) # Let the user actually see something!
driver.quit()

这导致了一个错误:selenium.common.exceptions.WebDriverException: 消息:u'找不到Chrome的可执行文件,路径是:

我还尝试了,

self.driver = webdriver.Chrome("./chromedriver")

这个方法可以用,但不是默认的用户配置文件。我还想知道,如何用这个方法打开新的窗口或新标签页?

谢谢。

2 个回答

0

要找出你的Chrome个人资料存放在哪里,首先打开Chrome浏览器,然后在地址栏里输入

chrome://version

。在“个人资料路径:”下面,你会看到你当前使用的个人资料的具体位置。例如:

~:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default
2

别光是从网站上复制粘贴东西!自己去看看那个文件夹里有什么东西吗?我猜是没有的。这就是为什么你去掉那部分后,程序能正常工作,因为它在找Chrome应该存在的地方!

说重点,你用错了!

如果你想给Selenium使用Chrome时换个不同的用户配置文件,你需要用到options这个类:

https://code.google.com/p/selenium/source/browse/py/selenium/webdriver/chrome/options.py

你需要用到add_argument这个函数。

为什么呢?

因为要给Chrome换个用户配置文件,你需要用特定的命令行来启动Chrome(具体来说就是--user-data-dir):

http://www.chromium.org/user-experience/user-data-directory

add_argument这个函数可以让你添加命令行参数。

所以如果你使用add_argument函数,Selenium会把你给的内容直接传递给Chrome,作为它的命令行参数的一部分。

撰写回答