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.

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 > > input.btn.btn-primary.btn-block



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 import By

import time
driver = None
    cpath = "e:\\projects\\headless\\chromedriver.exe"
    driver = webdriver.Chrome(cpath)
    e = driver.find_element(By.ID, "login_field")
    e = driver.find_element(By.ID, "password")
    e = driver.find_element(By.CSS_SELECTOR, "#login > form > > input.btn.btn-primary.btn-block")
    if driver is not None:

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.

Discussion (0)