Python:使用 cookie 登录 Selenium [英] Python: use cookie to login with Selenium
问题描述
我想做的是打开一个页面(例如youtube)并自动登录,就像我在浏览器中手动打开它一样.
What I want to do is to open a page (for example youtube) and be automatically logged in, like when I manually open it in the browser.
据我所知,我必须使用 cookie,问题是我无法理解.
From what I've understood, I have to use cookies, the problem is that I can't understand how.
我试图用这个下载 youtube cookie:
I tried to download youtube cookies with this:
driver = webdriver.Firefox(executable_path="driver/geckodriver.exe")
driver.get("https://www.youtube.com/")
print(driver.get_cookies())
我得到的是:
{'name': 'VISITOR_INFO1_LIVE', 'value': 'EDkAwwhbDKQ', 'path': '/', 'domain': '.youtube.com', 'expiry': None, 'secure': False, 'httpOnly': 真}
{'name': 'VISITOR_INFO1_LIVE', 'value': 'EDkAwwhbDKQ', 'path': '/', 'domain': '.youtube.com', 'expiry': None, 'secure': False, 'httpOnly': True}
那么我必须加载什么 cookie 才能自动登录?
So what cookie do I have to load to automatically log in?
推荐答案
您可以使用 pickle
将 cookie 保存为文本文件并稍后加载:
You can use pickle
to save cookies as text file and load it later:
def save_cookie(driver, path):
with open(path, 'wb') as filehandler:
pickle.dump(driver.get_cookies(), filehandler)
def load_cookie(driver, path):
with open(path, 'rb') as cookiesfile:
cookies = pickle.load(cookiesfile)
for cookie in cookies:
driver.add_cookie(cookie)
这篇关于Python:使用 cookie 登录 Selenium的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!