Python3 selenium opens the same instance of the Chrome browser every time it starts, enabling cookies-free login to the website

Posted May 27, 20202 min read

Original address https://www.cyberlight.xyz/passage/selenium-chome-same

The common method uses selenium, each time a new browser instance will be created, and cookies and other information that have been logged in cannot be saved. Today's business requires selenium to open the same browser every time. After consulting the information, write down the note for future reference.

This article loads the local user profile at the same time when selenium starts Chrome, so as to ensure that the Chrome has the same data information every time it starts. Taking Linux as an example here, it is also tried on Windows and Mac OS.

Operating environment:Ubuntu 20.04 LTS, Python 3.8.2, Chrome 83.0.4103.61

Write Chrome configuration code for selenium

First, you need to query the storage path of the Chrome configuration file on the local machine, and enter it in the Chrome address bar

chrome://version /

As shown below, find the profile path

As shown in the picture, my profile path is /home/cyberbolt/.config/google-chrome/Default(Windows and Mac paths are different, you can also query here)

Write the following Python code

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

option = webdriver.ChromeOptions()
option.add \ _argument('-user-data-dir =/home/cyberbolt/.config/google-chrome/Default') #Load the profile path obtained earlier
driver = webdriver.Chrome(chrome \ _options = option, executable \ _path = "/opt/google/chrome/chromedriver") #Start Chrome driver, here is Linux system, Windows and Mac OS fill in according to the actual path

After that, you can test it by yourself. Each time you will open the same browser, saving you a lot of trouble.

If you still do not understand the basic deployment method of selenium, please refer to Python3 selenium runs on Windows 10 or Python3 selenium runs on CentOS server . Thanks for reading, if you encounter any problems in the operation, please leave a message in the comment area!