python selenium操作打开的浏览器,Python Selenium:使用已经打开并使用登录凭证登录的浏览器...

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)

EDIT:

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:

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')

What you can do is:

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')

And you are now logged.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值