I'm new to Python and currently working on website authentication. I'm facing an issue where after adding cookies via Selenium (and confirming they appear in the browser), the site does not stay logged in upon page reload. When I used the requests package with the same cookies, authentication worked perfectly, but I can’t use requests here because the site relies heavily on JavaScript-rendered content, which requests cannot handle.
import json
import time
from selenium import webdriver
driver = webdriver.Chrome()
# 2. Download cookies from file
def load_cookies(filename):
try:
with open(filename, "r", encoding="utf-8") as file:
return json.load(file)
except Exception as e:
print(f"❌ Error for download cookies: {e}")
return []
# add cookie
def add_cookies(driver, cookies):
driver.get(";)
time.sleep(25)
for cookie in cookies:
selenium_cookie = {
'name': cookie['name'],
'value': cookie['value']
}
try:
driver.add_cookie(selenium_cookie)
print(selenium_cookie)
except Exception as e:
print(f"⚠️ Can not to add cookie {cookie['name']}: {str(e)}")
finally:
print('Cookies loaded')
time.sleep(25)
# refresh site for post cookies
driver.get(";)
time.sleep(60)
driver.save_screenshot("auth_check.png")
# 4. Using
cookies = load_cookies("cookie.json")
if cookies:
add_cookies(driver, cookies)
print("Site content:", driver.page_source)
driver.quit()
Additionally, this site supports login via the Authorization header, but I haven’t found a way to add this header in Selenium.
Question:
- Why doesn’t the site retain authentication after reloading in Selenium, even though cookies are present?
- How can I add the Authorization header in Selenium for direct authentication?
If I’m missing details or need to clarify anything, please let me know—this is my first post here, and I appreciate your patience!