How to use Selenium with Python?

You mean Selenium WebDriver?

Prerequisite: Install Python based on your OS

Install with following command

pip install -U selenium

And use this module in your code

from selenium import webdriver

You can also use many of the following as required

from import By
from import Select
from selenium.common.exceptions import NoSuchElementException

Here is an updated answer

I would recommend you to run script without IDE… Here is my approach

  1. USE IDE to find xpath of object / element
  2. And use find_element_by_xpath().click()

An example below shows login page automation

#ScriptName :
from selenium import webdriver

#Following are optional required
from import By
from import Select
from selenium.common.exceptions import NoSuchElementException

baseurl = ""
username = "admin"
password = "admin"

xpaths = { 'usernameTxtBox' : "//input[@name="username"]",
           'passwordTxtBox' : "//input[@name="password"]",
           'submitButton' :   "//input[@name="login"]"

mydriver = webdriver.Firefox()

#Clear Username TextBox if already allowed "Remember Me" 

#Write Username in Username TextBox

#Clear Password TextBox if already allowed "Remember Me" 

#Write Password in password TextBox

#Click Login button

There is an another way that you can find xpath of any object –

  1. Install Firebug and Firepath addons in firefox
  2. Open URL in Firefox
  3. Press F12 to open Firepath developer instance
  4. Select Firepath in below browser pane and chose select by “xpath”
  5. Move cursor of the mouse to element on webpage
  6. in the xpath textbox you will get xpath of an object/element.
  7. Copy Paste xpath to the script.

Run script –


You can also use a CSS selector instead of xpath. CSS selectors are slightly faster than xpath in most cases, and are usually preferred over xpath (if there isn’t an ID attribute on the elements you’re interacting with).

Firepath can also capture the object’s locator as a CSS selector if you move your cursor to the object. You’ll have to update your code to use the equivalent find by CSS selector method instead –


Leave a Comment