Python硒:使用已经打开并使用登录凭证登录的浏览器 [英] Python selenium: use a browser that is already open and logged in with login credentials
问题描述
有没有一种方法可以针对使用硒的python程序的不同运行,保留使用我的凭据打开并登录的浏览器,并在以后的运行中打开并使用?
Is there a way that for different runs of a python program that uses selenium I keep the browser that I have opened and logged in with my credentials, open and use in later runs?
我正在调试代码.每次需要在浏览器上使用我的凭据登录时.当前,每次我停止代码时,网络浏览器都会关闭.有没有办法保持我已经打开并登录的浏览器的副本打开,并在以后的调试中使用它,以便每次无需再次输入登录凭据?
I am debugging a code. On the browser each time I need to log in using my credentials. Currently, everytime I stop the code, the web-browser gets closed. Is there a way to keep a copy of browser that I have already open and logged in open and use it for my later debug so every time I don't need to enter my login credentials again?
我打开浏览器的代码如下:
My code that opens the browser looks like this:
driver = webdriver.Chrome(executable_path="/the_path/chromedriver", chrome_options=chrome_options)
driver.get(url)
实际上,此网站要求进行身份验证的方式如下: 首先,它要求输入用户名,然后我需要按继续按钮,然后要求输入密码,输入密码后,它会向我的手机发送一条SMS,在进入目标页面之前,我需要先输入它.
Actually, the way this website asks for authentication is as follows: First, it asks for the username, then I need to press the continue button, then it asks for the password, after entering the password, it sends an SMS to my phone, I need to enter it before it goes to the intended page.
推荐答案
好吧,由于该问题已被投票赞成,但我的重复问题的标记未被接受,我将在此处发布
Well, since this question is upvoted but my flag as duplicated question wasn't accepted I will post here the same exact answer I already posted for a similar question:
您可以使用 pickle
将Cookie保存为文本文件并加载之后:
You can use pickle
to save cookies as text file and load it after:
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)
使用如下脚本:
With a script like:
from selenium import webdriver
from afile import save_cookie
driver = webdriver.Chrome()
driver.get('http://website.internets')
foo = input()
save_cookie(driver, '/tmp/cookie')
您可以做的是:
- 运行此脚本
- 在(硒的)浏览器上,转到网站,登录
- 回到终端,输入任何内容,按回车键.
- 在
/tmp/cookie
上享受您的cookie文件.现在,您可以将其复制到代码存储库中,并在需要时将其打包到您的应用中.
- Run this script
- On the (selenium's) browser, go to the website, login
- Go back to your terminal, type anything hit enter.
- Enjoy your cookie file at
/tmp/cookie
. You can now copy it into your code repo and package it into your app if needed.
现在,在您的主要应用代码中:
So, now, in your main app code:
from afile import load_cookie
driver = webdriver.Chrome()
load_cookie(driver, 'path/to/cookie')
您现在已登录.
这篇关于Python硒:使用已经打开并使用登录凭证登录的浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!