Know how to write Selenium test using Python

Selenium supports many languages, in which python is one.

We have discussed how we can write and run selenium tests using java.

In this post, we will see how to run selenium scripts using python

 

Prerequisite

Download and setup python on windows OS

Download and setup python editor of your choice

 

Install selenium python package

Open cmd and type

This will install selenium python package in to local drive.

 

Sample selenium python script

Open Pycharm editor and create a new python file with extension .py, let’s firstSelPython.py

Explanation

from selenium import webdriver
Get all the webdriver implementation from selenium module, like we have import org.openqa.selenium.WebDriver; in java.

 

driver = webdriver.Chrome("<path of chrome driver>")
get the webdriver instance [as driver] and Invoke chrome browser, pass the chromedriver executable as parameter.

For Firefox
driver = webdriver.Firefox(executable_path="<path of firefox driver")
For IE
driver = webdriver.Ie(executable_path="<path of IE driver>")

 

To maximize browser window
driver.maximize_window()

 

Implicit wait in seconds
driver.implicitly_wait(30)

 

Wait for 50 sec before showing page time out error if page is not loaded
driver.set_page_load_timeout(50)

 

To load the url on browser
driver.get("https://sunilpatro1985.github.io")

 

Check if the title contains text “Sunil Patro”
assert "Sunil Patro" in driver.title

 

Locating an element and perform action
driver.find_element_by_link_text("About").click();

Other available locators are

Selenium python locators

 

To take screenshot, use save_screenshot() and specify the path to save the screenshot
driver.save_screenshot("c:\\Grid\\test.png")

 

Hard wait using native python method time.sleep()
time.sleep(3)

Stay tuned for more selenium tests using python!

References

https://selenium-python.readthedocs.io/

https://seleniumhq.github.io/selenium/docs/api/py/index.html

Content posted is based on learning or working experience, Share the post with others if find useful, Any queries?, leave comments or discuss on our facebook:qavalidation.com, Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: