不完全回答您的问题。但我发现这个link 非常有用。
另外,我看到您正在尝试包含用户目录选项。实际上,这不是必需的,因为它会在启动 chromedriver.exe 时创建一个临时目录。
了解chromedriver.exe - chromedriver.exe -h 的选项非常有帮助。
请参阅下面的示例,这对我来说效果很好。另外,我更喜欢在窗口中使用没有空格的路径,这有助于保持简单。
如果您使用--verbose 而不是--log-level=INFO,您将获得所有日志。
在 chromedriver 日志中,您可以看到为 chromedriver.exe 提供的默认参数。
import time, os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
exePath = './driver/chromedriver.exe'
logPath = os.path.join(os.getcwd(),'logs','chromedriver.log')
serviceArgs = ["--log-level=INFO", "--readable-timestamp", "--append-log"]
# service = Service(executable_path=exePath, log_path=logPath, service_args=serviceArgs)
service = Service(log_path=logPath, service_args=serviceArgs)
service.start()
print(service.service_url)
print(service.process.pid)
# driver = webdriver.Remote(service.service_url)
# Update to remove infobars and save password popups
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
prefs = {"profile.password_manager_enabled": False, "credentials_enable_service": False}
options.add_experimental_option("prefs", prefs)
caps = options.to_capabilities()
driver = webdriver.Remote(service.service_url, desired_capabilities=caps)
# driver = webdriver.Remote('http://localhost:63404')
driver.get('http://www.google.com/')
driver.maximize_window()
time.sleep(3) # Let the user actually see something!
driver.get("https://github.com")
time.sleep(3)
driver.back()
time.sleep(3)
driver.close()
driver.quit()
service.stop()
service.stop() 终止 chromedriver.exe 否则它将继续在后台运行。
我最后的文件夹结构如下:
rootDir
--driver/chromedriver.exe
--testchromedriver.py (with above code)
另外,创建为killchromedriver.py 文件以终止所有chromedriver.exe 实例,以防它们在后台运行。
import psutil # pip install psutil
for process in psutil.process_iter():
if(process.name() == 'chromedriver.exe'):
process.terminate()
print('chromedriver.exe was running and is now terminated')
更新:
添加删除信息栏和保存密码弹出窗口的选项