Monday, 7 May 2012

Example - Creating and running python (selenium2) script

Aim: How to start with the python scripts?

Difficulty Level: Medium

Pre-requisites:
  • Download the python from URL https://www.python.org/getit/ and install as well
  • Set the path of python into the System environment variable
  • Download the Autopy from URL http://pypi.python.org/pypi/autopy and install it as well
Steps to implementation:
  • Run the command for install the selenium easy_installSelenium
  • Record the script using selenium IDE
  • Export the recorded script into the python 2(web driver)
  • Save the script in .py extension
  • launch the command prompt
  • Go to the path where script is saved
  • Run the command python filename.py
Recorded script:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re

class Srcipt(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "http://foundation.time2test.co.uk/"
        self.verificationErrors = []
    
    def test_srcipt(self):
        driver = self.driver
        driver.get("http://foundation.time2test.co.uk/")
        driver.find_element_by_link_text("Log in").click()
        driver.find_element_by_id("user_login").clear()
        driver.find_element_by_id("user_login").send_keys("admin")
        driver.find_element_by_id("user_pass").clear()
        driver.find_element_by_id("user_pass").send_keys("time4test")
        driver.find_element_by_id("wp-submit").click()
        driver.find_element_by_css_selector("#menu-posts > div.wp-submenu > ul > li.wp-first-item > a.wp-first-item").click()
        driver.find_element_by_css_selector("a.button.add-new-h2").click()
        driver.find_element_by_id("title").clear()
        driver.find_element_by_id("title").send_keys("This is new post")
        driver.find_element_by_id("publish").click()
        driver.find_element_by_id("title").clear()
        driver.find_element_by_id("title").send_keys("Edit the post")
        driver.find_element_by_id("publish").click()
        driver.find_element_by_xpath("//div[@id='wphead-info']/div[@id='user_info']/p/a[2]").click()
    
    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True
    
    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()


Helpful Video:

Python2Video by time2test

No comments:

Post a Comment