selenium打開指定Chrome賬號

selenium打開指定Chrome賬號

  1. 獲取User Data路徑

    打開目標Chrome,在搜索欄輸入chrome://version,找到「個人資料路徑」。

    這裡獲取到的路徑為:C:\Users\Admin\AppData\Local\Google\Chrome\User Data,去掉後面的\Profile 2。

  2. 獲取–profile-directory值

    方法一:

    上圖User Data路徑末尾的「Profile 2」即為–profile-directory值。

    方法二:

    右鍵目標Chrome的桌面圖標,點擊屬性可看到–profile-directory值為「Profile 2」。

  3. 代碼演示

    from time import sleep
    
    from selenium import webdriver
    
    options = webdriver.ChromeOptions()
    # 步驟1獲取到的User Data路徑
    options.add_argument(r'--user-data-dir=C:\Users\Admin\AppData\Local\Google\Chrome\User Data')
    # 步驟2獲取到的--profile-directory值
    options.add_argument("--profile-directory=Profile 2")
    driver = webdriver.Chrome(options=options)
    
    driver.get("//www.baidu.com/")
    sleep(3)
    driver.quit()
    

    注意:此時已實現打開目標Chrome,但當電腦已有打開的Chrome瀏覽器時,運行到第10行時會報錯:user data directory is already in use, please specify a unique value for –user-data-dir argument, or don’t use –user-data-dir

    解決1:在運行腳本之前關閉所有Chrome實例。即關閉所有Chrome瀏覽器

    解決2(推薦):複製一份「Profile 2」文件夾到自己的目錄,專門用於自動化。

    複製到自己的目錄下:C:\Users\Admin\Desktop\AutoTest\ChromeData

  4. 修改代碼

    from time import sleep
    
    from selenium import webdriver
    
    options = webdriver.ChromeOptions()
    # 修改路徑為自己的目錄
    options.add_argument(r'--user-data-dir=C:\Users\Admin\Desktop\AutoTest\ChromeData')
    options.add_argument("--profile-directory=Profile 2")
    driver = webdriver.Chrome(options=options)
    
    driver.get("//www.baidu.com/")
    sleep(3)
    driver.quit()
    

    至此,解決了多開Chrome時運行腳本報錯的問題~