DEV Community

Tony Colston
Tony Colston

Posted on

using Seleniun to login to a website part 2

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">
Enter fullscreen mode Exit fullscreen mode

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">
Enter fullscreen mode Exit fullscreen mode

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…">
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

XPath:

//*[@id="login"]/form/div[3]/input[4]
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)