How to use a specific Chrome profile in Python Selenium
Selenium is a Python automation module used to automate and test web applications. In this Answer, we'll learn how to use a specific Chrome profile in Selenium using Python.
Selenium opens Chrome by default in incognito mode. If we want to open it with any pre-existing settings like logins, Chrome extensions, etc., we can tell Selenium to open Chrome with a specific Chrome profile by providing details to the ChromeOptions object.
Let's take a look at an example of this.
Code example
from selenium import webdriverfrom selenium.webdriver.chrome.options import Options#create chromeoptions instanceoptions = webdriver.ChromeOptions()options.add_argument("--headless")options.add_argument("--no-sandbox")#provide location where chrome stores profilesoptions.add_argument(r"--user-data-dir=/home/username/.config/google-chrome")#provide the profile name with which we want to open browseroptions.add_argument(r'--profile-directory=Profile 3')#specify where your chrome driver present in your pcdriver = webdriver.Chrome(options=options)#provide website url heredriver.get("https://omayo.blogspot.com/")#find element using its idprint(driver.find_element("id","home").text)
Code explanation
In the above code snippet:
Line 5: We create an instance of the
ChromeOptionsclass and assign it to theoptionsvariable.Line 10: We provide the path where Chrome stores profiles as a value to the argument
–user-data-dir.In a Linux based system, Chrome stores profiles in the path
/home/username/.config/google-chrome.In Windows, Chrome stores profiles in the path
C:\Users\your user name here\AppData\Local\Google\Chrome\User Data.
Line 13: We add the argument
–profile-directorywith value as the directory name of the Chrome profile to theoptionsvariable. Here, we specify to use ChromeProfile 3.Line 16: We create an instance of a web driver and assign it to the
drivervariable.Line 19: We open the webpage using the
get()method.Line 22: We find an element with the id
homeand display its value to test it.
Free Resources