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
Chose an editor from list of python editor
Configure & run python on PyCharm [my preference]
Configure & run python on Visual studio code [Watch video]
Install selenium python package
Open cmd / terminal and type
pip install -U selenium
For Mac OS – pip3 install -U selenium
This will install selenium python package in to local drive or local project repo
Sample selenium python script
Open Pycharm editor and create a new python file with extension .py, let’s firstSelPython.py
from selenium import webdriver import time # driver = webdriver.Firefox(executable_path="C:\\Grid\\geckodriver.exe") # driver = webdriver.Ie(executable_path="C:\\Grid\\IEdriverserver.exe") driver = webdriver.Chrome("C:\\Grid\\chromedriver.exe") driver.maximize_window() driver.implicitly_wait(30) driver.set_page_load_timeout(50) driver.get("https://qavbox.github.io/demo") assert "QAVBOX" in driver.title driver.find_element_by_link_text("SignUp Form").click(); driver.save_screenshot("c:\\Grid\\test.png") time.sleep(3) driver.quit();
To run this code
Open terminal, navigate to project repo and type
python3 <Filename>.py
For windows – python <filename>.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 Firefoxdriver = webdriver.Firefox("<path of firefox driver")
Note –
Example –
For MacOS –
driver = webdriver.Chrome("/Users/SomeFolder/chromedriver")
For Windows OS
driver = webdriver.Chrome("C:\\SomeFolder\\chromedriver.exe")
To maximize browser windowdriver.maximize_window()
Implicit wait in secondsdriver.implicitly_wait(30)
Wait for 50 sec before showing page time out error if page is not loadeddriver.set_page_load_timeout(50)
To load the url on browserdriver.get("https://qavbox.github.io/demo")
Check if the title contains text “QAVBOX”assert "QAVBOX" in driver.title
Locating an element and perform actiondriver.find_element_by_link_text("SignUp Form").click();
Other available locators are
To take screenshot, use save_screenshot() and specify the path to save the screenshotdriver.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
2 Comments