【问题标题】:How to Submit HTTP authentication with Selenium python-binding webdriver如何使用 Selenium python-binding webdriver 提交 HTTP 身份验证
【发布时间】:2011-08-11 07:10:27
【问题描述】:

我正在使用 Selenium python 绑定来为我们的 Web 应用程序设置自动化测试。我在测试版服务器上测试网络时遇到了一个问题,因为它需要对 Intranet 用户名和密码进行 HTTP 身份验证。

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://somewebsite.com/")

我需要在访问http://somewebsite.com/时为弹出对话框提交用户名和密码

有没有一种巧妙的方法可以做到这一点?

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    我已经找到了解决这个问题的方法:

    from selenium import webdriver
    
    profile = webdriver.FirefoxProfile()
    profile.set_preference('network.http.phishy-userpass-length', 255)
    driver = webdriver.Firefox(firefox_profile=profile)
    driver.get("https://username:password@somewebsite.com/")
    

    FirefoxProfile 部分用于关闭确认对话框,因为默认情况下 Firefox 会显示一个弹出对话框以防止钓鱼。

    【讨论】:

    • 这个解决方案也对我有用(我在 Windows XP SP3 上运行最新版本的 Firefox,使用 Python 和 selenium)。
    • 在 docker hub 3.4.0 版的 docker 容器中使用 pyhon3.6、selenium==3.3.1 和 selenium/standalone-firefox 仍然对我有用。
    【解决方案2】:

    另一种解决方案:

    使用 python 请求登录,获取 cookie,并将 cookie 推送到 selenium 的浏览器中

    import requests from selenium import webdriver from requests.auth import HTTPBasicAuth session = requests.Session() www_request = session.get('http://example.com', auth=HTTPBasicAuth('username','password'), allow_redirects=False) driver = webdriver.Remote(...) #chrome needed to open the page before add the cookies driver.get('http://example.com') cookies = session.cookies.get_dict() for key in cookies: driver.add_cookie({'name': key, 'value': cookies[key]}) driver.get('http://example.com')

    【讨论】:

    • 这只会将 cookie 从会话复制到 webdriver。虽然这在某些情况下可能有效(取决于后端的设置方式),但在所有请求都需要 authorization 标头(不仅仅是第一个请求)的情况下,这将不起作用。
    猜你喜欢
    • 2016-05-02
    • 2012-03-04
    • 2016-08-10
    • 2013-10-18
    • 2022-08-19
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多