TAGS :Viewed: 9 - Published at: a few seconds ago

[ How to log in programmatically and then switch to WebDriver with python ]

I know that the "log in programmatically" question has been asked before, but here is what I am trying to do.

I have many python functional tests that login each time to the web app to execute each scenario. The log in has come to be the most tested feature and I would like to skip it. That means to avoid the UI to save time. I am trying to login by sending a post request using the Requests python library and then switch , somehow , to webdriver and continue the test in the authorized part.

Here is what i have done so far (the code is from another SO post).

def login_robot(username,password):
    import requests
    # Fill in your details here to be posted to the login form.
    payload = {'username': username, 'password': password}
    login_url = "https://www.webapp.com/login/index.php"

    # Use 'with' to ensure the session context is closed after use.
    with requests.Session() as s:
        s.post(login_url, data=payload)

        # # An authorised request.
        r = s.get('http://www.webapp.com/wall.php')
        print r.text

The r.text prints the page behind the login correctly. How should I connect this with the webdriver launching an actual firefox instance? Are these two , two entirely different browser instances?

Answer 1

Probably not the most "programmatic" method, but the most simple solution imo would be to make a rudimentary "login_form.html" that selenium can use to login

<form id="login" action="https://www.webapp.com/login/index.php" method="post">
    <input type="text" name="username" value="wehappyfew" />
    <input type="password" name="password" value="qwerty1234" />

then just do:

driver.get( "file:///C:/location/of/login_form.html" )
driver.find_element_by_css_selector( "form#login" ).submit()