9

I'm using Selenium python binding to setup an automation test for our web application. I'm facing a problem while testing the web on beta server because it requires HTTP authentication for an intranet username and password.

from selenium import webdriver

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

I need to submit a username and a password for the popup dialog upon accessing http://somewebsite.com/

Is there a neat way to do this?

2 Answers2

10

I have found a solution to this question:

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/")

The FirefoxProfile part is to dismiss the confirmation dialog because by default Firefox will show a popup dialog to prevent pishing.

  • this solution worked for me too (I run last version of Firefox on Windows XP SP3, using Python and selenium). –  Aug 01 '14 at 09:32
  • http://stackoverflow.com/questions/10395462/handling-browser-authentication-using-selenium – Ulf Gjerdingen Feb 03 '17 at 09:17
  • It is still working for me using pyhon3.6, selenium==3.3.1 and selenium/standalone-firefox inside a docker container of docker hub version 3.4.0. – Yeray Álvarez Romero May 12 '17 at 13:25
4

Another solution:

login with python requests, get the cookies, and push the cookies into the selenium's browser



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


Balázs Zámbó
  • 615
  • 6
  • 2
  • This only copies cookies from the session across to the webdriver. While this may work in some cases (depending on how the backend is setup), this won't work in cases where the `authorization` header is required for all requests - not just the first. – Johann Burgess Sep 02 '20 at 05:54