如何使用Selenium Python绑定的WebDriver提交HTTP身份验证

9

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

from selenium import webdriver

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

在访问http://somewebsite.com/时,我需要提交用户名和密码来打开弹出窗口。

有没有一种简洁的方法来实现这个功能?

2个回答

10
我已经找到了这个问题的解决方案:
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)。 - user3522371
https://dev59.com/Smkv5IYBdhLWcg3wvDJF - Ulf Gjerdingen
我仍然使用python3.6,selenium==3.3.1和selenium/standalone-firefox在docker hub版本3.4.0的docker容器中工作良好。 - Yeray Álvarez Romero

4

另一种解决方案:

使用Python requests登录并获取cookies,然后将cookies添加到Selenium浏览器中



    import requests
    from selenium import webdriver
    from requests.auth import HTTPBasicAuth
session = requests.Session() #登录并获取cookies www_request = session.get('http://example.com', auth=HTTPBasicAuth('username','password'), allow_redirects=False)
driver = webdriver.Remote(...) #先打开页面再添加cookies(chrome需要) driver.get('http://example.com')
#获取cookies并添加到浏览器中 cookies = session.cookies.get_dict() for key in cookies: driver.add_cookie({'name': key, 'value': cookies[key]})
#重新打开页面以便使用cookies driver.get('http://example.com')

这只是将会话中的 cookies 复制到 webdriver 中。虽然在某些情况下可能有效(取决于后端设置方式),但在需要所有请求(而不仅仅是第一个请求)都需要 authorization 标头的情况下,这种方法将无法奏效。 - Johann Burgess

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接