loading...

using Seleniun to login to a website part 2

tonetheman profile image Tony Colston ・2 min read

Today we will look at another website and decide how we would login with Selenium. Github will be our target. First you need to find a good place to login.

https://github.com/login

First the name field.

<input type="text" name="login" id="login_field" class="form-control input-block" tabindex="1" autocapitalize="off" autocorrect="off" autofocus="autofocus">

The choice is obvious. We will use the id field as the locator, "login_field."

<input type="password" name="password" id="password" class="form-control form-control input-block" tabindex="2">

Again here the choice is obvious we will use the id again and it is "password."

Now the button...

<input type="submit" name="commit" value="Sign in" tabindex="3" class="btn btn-primary btn-block" data-disable-with="Signing in…">

Here is our first example where ID is not available. Sigh. Why did github not put an ID on the sign in button? We could pick the name field but to make it interesting we are going to use something else.

Lets look at two other choices we could use.

CSS selector:

#login > form > div.auth-form-body.mt-3 > input.btn.btn-primary.btn-block

XPath:

//*[@id="login"]/form/div[3]/input[4]

Both choices are tied directly to the DOM structure. If the designer for this page adds even a single div to the page above the button neither the CSS Selector or the XPath will work.

In the example below I chose the CSS Selector.



from selenium import webdriver
from selenium.webdriver.common.by import By

import time
driver = None
try:
    cpath = "e:\\projects\\headless\\chromedriver.exe"
    driver = webdriver.Chrome(cpath)
    driver.get("https://github.com/login")
    e = driver.find_element(By.ID, "login_field")
    print(e)
    e.send_keys("github_selenium")
    e = driver.find_element(By.ID, "password")
    e.send_keys("githubsupersecretpasswordhere")
    e = driver.find_element(By.CSS_SELECTOR, "#login > form > div.auth-form-body.mt-3 > input.btn.btn-primary.btn-block")
    driver.save_screenshot("github.png")
    e.click()
    driver.save_screenshot("github.png")
finally:
    if driver is not None:
        driver.quit()

Once you run the program you will end up with two screenshots so you can verify your program worked as expected. You will get a login failure in this case since I used a bogus username/password.

Posted on by:

tonetheman profile

Tony Colston

@tonetheman

wanna be gamedev ... all around nerd and dev

Discussion

pic
Editor guide