I am running Selenium (4.16.0) from a Python Jupyter Notebook on Mac OSX to automate printing a news article to PDF in Chrome (version 120.0). My code successfully opens Chrome with the Default profile and loads the article, but does NOT sign me into websites even when I have credentials for them saved in that Chrome profile:
from selenium import webdriver
import json, base64
import pickle
import time
url = "https://www.wsj.com/tech/apple-wins-temporary-reprieve-as-u-s-court-pauses-watch-ban-b3b69830?mod=hp_lead_pos1"
chrome_profile_path = "Users/{myusername}/Library/Application Support/Google/Chrome"
# Create a ChromeOptions instance
chrome_options = webdriver.ChromeOptions()
# Set Chrome options to access Default profile & enable printing
chrome_options.add_argument('--kiosk-printing')
chrome_options.add_argument("user-data-dir=/" + chrome_profile_path)
chrome_options.add_argument("--profile-directory=Default")
# Create a Chrome driver that accesses the default profile
driver = webdriver.Chrome(options=chrome_options)
print("Navigating to webpage...")
# Navigate to the article of interest
driver.get(url)
print("Opened webpage. Pausing to allow it to load...")
time.sleep(3)
print("Pause complete. Getting cookies...")
cookies = driver.get_cookies()
for cookie in cookies:
driver.add_cookie(cookie)
time.sleep(3)
print("Printing page to PDF...")
# Prints the page to PDF
result = driver.execute_cdp_cmd('Page.printToPDF', {'landscape': True, 'printBackground': True})
# Save the PDF to a file
with open('article.pdf', 'wb') as file:
file.write(base64.b64decode(result['data']))
# Close the browser
driver.quit()
print("Process complete.")
I configured my code to open Chrome with the default profile because my understanding was that this would automatically log me into the relevant news site.
The Default profile stores my credentials for this news site. I confirmed this by manually logging into the news site, quitting Chrome, relaunching, and returning to the same news site - I am already signed in without having to enter credentials.
However, when I quit Chrome and run this code, Chrome launches using my Default profile (I can see this in the top-right hand corner of Chrome) but does not log me into the news site.
To try to overcome this, I added code to ensure the relevant cookies are being accessed and loaded; this does not resolve the issue.
I would be grateful for any advice on how to ensure I remain logged into sites when accessing them using webdriver.
Note: I am running executing the code from a Notebook in a different browser and fully quitting Chrome each time I try this.