Carpetfizz Carpetfizz - 1 year ago 55
Python Question

How to use Selenium with Python?

How do I set up Selenium to work with Python? I just want to write/export scripts in Python, and then run them. Are there any resources that will teach me how to do this? I tried googling, but the stuff I found were either referring to an outdated version of Selenium (RC), or an outdated version of Python.

Answer Source

You mean selenium webdriver?


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 - python

You can also use css_selector instead of xpath. Firpath will also capture css_selector if tou move cursor to the object. You will have to use then - find_element_by_css_selector(css_selector)