如何通过 Selenium-Python 恢复浏览器会话或使用现有浏览器窗口? [英] How to resume browser session or use existing browser window with Selenium-Python?

查看:66
本文介绍了如何通过 Selenium-Python 恢复浏览器会话或使用现有浏览器窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些看起来像这样的代码:

I've got some code that looks like this:

print 'Starting browser'
browser = webdriver.Firefox()

print 'Loading %s' % base_url
browser.get(base_url)

try:
    username_el = browser.find_element_by_css_selector('#username')
    username_el.send_keys(credentials['username'])
    password_el = browser.find_element_by_css_selector('#password')
    password_el.send_keys(credentials['password'])
    password_el.send_keys(Keys.RETURN)
    print 'Logging in'
    browser.get(base_url)
except NoSuchElementException:
    print 'Already logged in'
    pass

问题在于它每次都必须登录(永远不会触发异常).这有两个问题:

The problem is that it has to log in every time (never trips the exception). This has two problems:

  1. 这使我的测试需要更长的时间,因为我每次都必须等待它登录
  2. 它比它需要的更多地访问服务器

所以,我想要么保存并恢复我的浏览器会话,要么让浏览器保持打开状态并让 Selenium 控制它.

So, I'd like to either save and resume my browser session, or leave the browser open and have Selenium take control of that.

这可能吗?如果是这样,如何?

Is this possible? If so, how?

推荐答案

我会尝试使用 get_cookies() 获取任何会话 cookie,将其保存在浏览器会话(磁盘或其他)之间持久存在的某个地方,然后重新 -当您启动新的浏览器会话时,使用 add_cookie() 添加 cookie.

i'd try using get_cookies() to grab any session cookies, saving that somewhere that'll persistent between browser sessions (disk or whatever), and re-adding the cookies using add_cookie() when you pull up a new browser session.

还没有测试过这个...

haven't tested this though...

这篇关于如何通过 Selenium-Python 恢复浏览器会话或使用现有浏览器窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆