admin管理员组文章数量:1355522
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!
本文标签: Problem with authorization on the site via Selenium on PythonStack Overflow
版权声明:本文标题:Problem with authorization on the site via Selenium on Python - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743976906a2570915.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论