Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

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.

1 Answer

0 votes
by (62.9k points)
edited by

I would recommend you 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 : Login.py

#---------------------

from selenium import webdriver

#Following are optional required

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import Select

from selenium.common.exceptions import NoSuchElementException

baseurl = "https://www.intellipaat.com"

username = "admin"

password = "admin"

xpaths = { 'username TxtBox' : "//input[@name='username']",

           'password TextBox' : "//input[@name='password']",

           'submitButton' :   "//input[@name='login']"

         }

mydriver = webdriver.Firefox()

mydriver.get(baseurl)

mydriver.maximize_window()

#Clear Username TextBox if already allowed "Remember Me" 

mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).clear()

#Write Username in the Username TextBox

mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).send_keys(username)

#Clear Password TextBox if already allowed "Remember Me" 

mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).clear()

#Write Password in password TextBox

mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)

#Click Login button

mydriver.find_element_by_xpath(xpaths['submitButton']).click()

There is another way that you can find XPath of any object -

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

Run script -

python Login.py

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

find_element_by_css_selector(css_selector) 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...