[365Gist] Repeating session via Cookies — Selenium (Python)

Thongchan Thananate
2 min readApr 25, 2022

Using Selenium automation is cool, but struggling at login screen every run is not cool at all. We will login once and use that cookie until the session expired.

Let’s go easy in Python. (can applied yo your fav language)

The code working in this order:
Step 1.) using Chrome to open facebook.com you may use any favorite webdriver or using old-fashioned:

path = “C:\chromedriver_win32\chromedriver.exe”
driver = webdriver.Chrome(path)

Step 2.) build function get cookies to get and return in List.

Step 3.) making csv file by inspecting webpage.
For Chrome user, go to Application > Storage > Cookies
For Safari user, go to Storage > Cookies

then, copy all (ctrl+a) and paste into Excel, we will use column ‘Name’, ‘Value’, and ‘Domain’,
the rest just delete it,
save the file as .csv,
and to make sure the reader encoding correctly we put encoding='utf-8-sig' in the code

Step 4.) read the cookie file from the same directory, I saved as cookie.csv

Step 5.) cookies have multiple lines, so using for loop to put in the driver.

Step 6.) make sure that cookies are put into the driver by refresh() once.

Boom! now you can automate test any login-needed websites.
Just beware that some web has cookie expiration time, updating cookie.csv is just fine. And some website might detect you as a bot, deal with it.

Ready, Set, Python!

--

--

Thongchan Thananate

People might laugh at it or call it foolish logic, but that’s enough for me. That’s what romanticism is about!