我正在尝试使用我的默认用户使用 selenium python 库打开一个网页,脚本使用默认用户很重要,但是如果我的 chrome 浏览器已经打开,脚本会崩溃并给我这个错误:
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: user data directory is already in use, please specify a unique value for --user-data-dir argument, or don't use --user-data-dir
我已经尝试了这里给出的所有解决方案:
如果另一个 chrome 实例打开,Selenium chromedriver 将不会启动 URL
Selenium 不会在新选项卡中打开新 URL(Python 和 Chrome)
并读到旧版 chromedriver 版本中存在错误,但已在 chrome 74(我正在使用)中修复: https ://github.com/SeleniumHQ/docker-selenium/issues/741
from selenium import webdriver
import time
from getpass import getuser
def run():
# Chrome driver path
chromedriver = r'C:\Users\user1\Downloads\chromedriver_win32\chromedriver_new.exe'
# Get chrome webdriver options and set open the browser as headless
chrome_options = webdriver.ChromeOptions()
#chrome_options.add_argument("--headless")
# Fix for selenium Issue 2907
#chrome_options.add_argument('--log-level=3')
#chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])
# Load current user default profile
current_user = getuser()
chrome_options.add_argument(
r"--user-data-dir=C:\Users\{}\AppData\Local\Google\Chrome\User Data".format(current_user))
# didable "Chrome is being controled by an automated test software"
chrome_options.add_argument('disable-infobars')
# get Chrome to stay open
chrome_options.add_experimental_option("detach", True)
# open browser with options and driver
driver = webdriver.Chrome(options=chrome_options, executable_path=chromedriver)
driver.get(r'https://www.youtube.com/watch?v=dQw4w9WgXcQ')
if __name__ == '__main__':
run()
如果我在没有 chrome 浏览器的情况下运行它,打开它很好,如果不是它崩溃