Selenium with Python
Introduction
This guide shows how to use PyCharm, Python, Selenium, JavaScript, and unittest together.
Basic knowledge of
Python
and
JavaScript
Selenium's core WebDriver methods are largely language-independent; they are covered in
«Selenium basics»
These examples use PyCharm. See
how to add Selenium to PyCharm
You can use another IDE or run the tests on
Linux
. If you run Selenium from
Windows Subsystem for Linux (WSL)
configure Linux GUI support first (for example, WSLg or an X server) before launching a visible browser. Headless mode is often simpler for CI.
The examples start with direct WebDriver tasks, then move on to JavaScript-assisted DOM interaction and test automation with unittest.
Installation
First, make sure that Python is installed
python3 --version
Python 3.8.5
Then make sure that pip is installed
pip3 --version
pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)
If both are available, install Selenium as a regular Python package with pip.
pip3 install selenium
Collecting selenium Downloading selenium-3.141.0-py2.py3-none-any.whl (904 kB) |████████████████████████████████| 904 kB 8.7 MB/s Requirement already satisfied: urllib3 in /usr/lib/python3/dist-packages (from selenium) (1.25.8) Installing collected packages: selenium Successfully installed selenium-3.141.0
Choose a browser driver
After installing Selenium, download the driver for the browser you want to automate.
This step is the same regardless of which programming language you use.
See the detailed instructions in
Selenium basics
Once the driver directory is on PATH, create the browser driver in your Python code.
Firefox
Firefox uses geckodriver, which you can start like this:
from selenium import webdriver
driver = webdriver.Firefox()
Chrome works similarly. You can choose any variable name instead of driver, such as chrome_driver or firefox_driver.
from selenium import webdriver
driver = webdriver.Chrome()
Find elements
There are several ways to locate elements. The examples use Selenium's By locator class:
from selenium.webdriver.common.by import By
Selenium 4 API note: the find_element_by_* and find_elements_by_* methods shown in some older examples are deprecated and are not available in current Selenium releases. Use the By locator argument instead, for example driver.find_element(By.ID, "loginButtonId") or driver.find_elements(By.CLASS_NAME, "title").
A simple test
Open a website and verify that its Russian-language page title contains «О Финляндии и путешествиях». Then locate an image by class name and by CSS selector.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
driver.get("https://www.heihei.ru/")
assert "О Финляндии и путешествиях" in driver.title
image = driver.find_element_by_class_name("w100");
# Returns only the first element with the class
image2 = driver.find_element_by_css_selector('img.w100')
# Returns only the first element with the css selector
print('image2: ')
print(image2)
Headless mode
To run Selenium without opening a visible browser window, enable the headless option.
This is useful when running tests in a CI/CD pipeline.
Import Options to configure Chrome:
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
You can make headless mode conditional on a command-line argument and log which mode is active.
chrome_options = Options()
if headless == True:
chrome_options.add_argument("--headless")
print("Running in headless mode")
else:
print("Running head over hills")
driver = webdriver.Chrome(options=chrome_options)
Click a button
To click a button, locate it and call click().
For example, find a button with the new-button class and click it.
driver.find_element_by_css_selector('button.new-button').click()
You can also locate a button by ID:
driver.find_element_by_id('loginButtonId').click()
Or store the located element in a variable and call click() separately:
loginButton = driver.find_element_by_id('loginButtonId')
loginButton.click()
Find an element by text
Goal: click the button labelled LOGIN.
The text is inside a div with the title class. There are several such elements, and the button's position is not known in advance.
Find all elements with the title class, then select the one whose text matches:
title_class = driver.find_elements_by_class_name("title")
for el in title_class:
if el.text == "LOGIN":
login_button = el
login_button.click()
Wait for an element to load
Suppose you need to wait for elements with the class
Buttons
and are willing to wait up to ten seconds.
driver.implicitly_wait(10)
buttons = driver.find_elements_by_class_name("Buttons")
The driver continues as soon as the elements appear; it does not always wait the full ten seconds.
An implicit wait retries element lookups until an element is found or the timeout expires. The timeout is configured for the driver session.
Fill out a form
This example fills out a website form. The same approach can help you periodically check that a form you maintain is still working.
It uses a renovation inquiry form for
an apartment renovation on the Costa del Sol
on
HeiHei.ru
First verify that the page title contains “Costa del Sol”, then fill in the form automatically.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
driver.get("https://www.heihei.ru/Spain/renovation/costa_del_sol/")
assert "Коста-дель-Соль" in driver.title
driver.find_element_by_id('container')
driver.find_element_by_class_name('imgfull')
municipality_list = Select(driver.find_element_by_name('municipality'))
municipality_list.select_by_visible_text('Марбелья')
area_list = Select(driver.find_element_by_name('price'))
area_list.select_by_value('area-larger100')
bedrooms_list = Select(driver.find_element_by_name('bedrooms'))
bedrooms_list.select_by_value('3-bedroom')
meetingplace_list = Select(driver.find_element_by_name('meetingplace'))
meetingplace_list.select_by_visible_text('Хельсинки')
your_name_form = driver.find_element_by_name('your_name')
your_name_form.send_keys('Andrei')
email_form = driver.find_element_by_name('email')
email_form.send_keys('heihei@heihei.ru')
message_form = driver.find_element_by_name('message')
message_form.send_keys('TEST Message')
sum_form = driver.find_element_by_name('sum')
sum_form.send_keys('100')
driver.find_element_by_css_selector('.img40c.bookingbutton').click()
Create a test user
This end-to-end example opens the site in Chrome.
It signs in, opens Tools in the top menu, and selects User Profiles.
It fills out the form, saves the new user, and checks for a duplicate-name warning or an unhandled application error.
The page's dynamic controls are located with JavaScript, assigned stable IDs, and then accessed through Selenium WebDriver.
Treat this as a demonstration rather than a copy-and-run script: it uses site-specific selectors and fixed delays that should be replaced with robust waits.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome()
driver.get("http://your_url.ru/test/")
driver.set_window_size(1920, 1024)
driver.find_element_by_id('someDivId')
time.sleep(2)
driver.execute_script("""
div1 = document.getElementById('someDivId');
div1.style.backgroundColor = 'red';
""")
time.sleep(2)
driver.execute_script("""
window.scrollBy(0,1000)
div1 = document.getElementById('someDivId');
div1.style.backgroundColor = 'red';
div2 = div1.children;
div2[0].style.backgroundColor = 'green';
div3 = div2[0].children;
div3[0].style.backgroundColor = 'yellow';
table1 = document.getElementsByClassName('v-formlayout-margin-top');
array1 = document.getElementsByClassName('v-textfield');
array1[0].style.backgroundColor = 'violet';
array1[0].style.padding = '40px';
array1[0].id = 'usernameId';
array1[1].style.backgroundColor = 'pink';
array1[1].style.padding = '40px';
array1[1].id = 'passwordId';
idCandidates = document.getElementById('some-uid-5')
div1.style.backgroundColor = 'grey';
button1 = document.getElementsByClassName('v-button');
button1[0].id = 'loginButtonId';
console.log(div2.length);
""")
usernameForm = driver.find_element_by_id('usernameId')
usernameForm.send_keys('user')
passwordForm = driver.find_element_by_id('passwordId')
passwordForm.send_keys('password')
loginButton = driver.find_element_by_id('loginButtonId')
loginButton.click()
print("Logged in successfully!")
time.sleep(4)
driver.execute_script("""
topMenuElements = document.getElementsByClassName('v-menubar-menuitem');
toolsButton = topMenuElements[5];
toolsButton.style.color = 'red';
toolsButton.id = 'topToolsButton';
""")
topToolsButton = driver.find_element_by_id('topToolsButton')
topToolsButton.click()
print("Tools menu entered!")
time.sleep(4)
driver.execute_script("""
toolsButtonBlockOfOptions = document.getElementsByClassName('v-menubar-submenu-top-menu');
console.log('------------------------------------------ '+toolsButtonBlockOfOptions);
toolsButtonBlockOfOptions[0].style.color = 'violet';
toolsButtonBlockOfOptions[0].id = 'toolsDropDownDiv';
toolsDropDownOptions = toolsButtonBlockOfOptions[0].children;
console.log('-----------------------------------------2 '+toolsButtonBlockOfOptions[0]);
toolsDropDownOptions[1].style.color = 'orange';
toolsDropDownOptions[1].id = 'usersProfilesId';
""")
time.sleep(2)
userProfilesButton = driver.find_element_by_id('usersProfilesId')
userProfilesButton.click()
print("User Profiles menu entered!")
time.sleep(4)
driver.execute_script("""
toolsAddUserButtonCandidates = document.getElementsByClassName('v-button');
toolsAddUserButtonCandidates[2].style.color = 'red';
toolsAddUserButtonCandidates[2].style.paddingRight = '150px';
toolsAddUserButtonCandidates[2].id = 'addUserButtonId';
""")
time.sleep(2)
addUserButton = driver.find_element_by_id('addUserButtonId')
addUserButton.click()
time.sleep(2)
driver.execute_script("""
userNamFieldCandidates = document.getElementById('some-uid-85');
userNamFieldCandidates.style.color = 'red';
userNamFieldCandidates.style.paddingRight = '150px';
//userNamFieldCandidates[0].id = '';
""")
addUserUsername = driver.find_element_by_id('some-uid-85')
addUserUsername.send_keys('testUserSelenium')
time.sleep(2)
addUserFirstName = driver.find_element_by_id('some-uid-87')
addUserFirstName.send_keys('FirstNameSelenium')
time.sleep(2)
addUserLastName = driver.find_element_by_id('some-uid-89')
addUserLastName.send_keys('LastNameSelenium')
time.sleep(2)
addUserPassword = driver.find_element_by_id('some-uid-91')
addUserPassword.send_keys('password1')
addUserUserTagId = driver.find_element_by_id('some-uid-93')
addUserUserTagId.send_keys('12345')
driver.execute_script("""
userGroupSelectBlockCandidates = document.getElementsByClassName('v-select-select');
userGroupSelectBlockCandidates[0].style.color = 'red';
userGroupSelectBlockCandidates[0].style.paddingRight = '150px';
userGroupSelectOptions = userGroupSelectBlockCandidates[0].children;
userGroupSelectOptions[1].style.color = 'blue';
userGroupSelectOptions[1].id = 'userGroupSelectOptionAdminId';
""")
time.sleep(2)
selectUserGroupAdmin = driver.find_element_by_id('userGroupSelectOptionAdminId')
selectUserGroupAdmin.click()
#similar code exists - need to replace with a function if possible
driver.execute_script("""
saveButtonCandidates = document.getElementsByClassName('v-button');
saveButtonCandidates[4].style.backgroundColor = 'green';
saveButtonCandidates[4].style.color = 'red';
saveButtonCandidates[4].style.margin = '150px';
saveButtonCandidates[4].style.padding = '150px';
saveButtonCandidates[4].id = 'saveButtonId';
""")
time.sleep(2)
saveButton = driver.find_element_by_id('saveButtonId')
saveButton.click()
print("Tried to create new user!")
time.sleep(2)
if driver.find_elements_by_xpath("//*[contains(text(), 'Given user name is already in use')]"):
print("WARNING LOG:\n User with this name already exists \nWARNING LOG END \n ")
if driver.find_elements_by_xpath("//*[contains(text(), 'RpcInvocationException')]"):
print("ERROR LOG:\n RpcInvocationException \nERROR LOG END \n ")
#driver.close()
Upload a file
To upload a file with Selenium, you do not need to click the upload button.
Locate the file input and use send_keys() with the file's path.
In this example, the input has the ID inputElement. If it has no ID, you can add one with
JavaScript
inputElement = driver.find_element_by_id(inputElementId)
inputElement.send_keys("C:\\Users\\username\\Documents\\Projects\\projectName\\products_to_import-ANSI.csv")
Test without a testing framework
This example clicks several items in the top menu, so a helper function accepts a menu name (such as Tools), looks up its index in a dictionary, and clicks the matching item.
It also uploads a file. No test framework is used here, so the script relies on its own logging and checks.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import requests
import time
import random
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
url2 = "http://someUrl:4880/path/"
failedToConnect = False
r = 0
try:
r = requests.get(url2)
except:
print("Tried to connect to server but failed")
failedToConnect = True
#headless = True
headless = False
def testprojectNameVVM(headless) :
# driver = webdriver.Chrome()
chrome_options = Options()
if headless == True:
chrome_options.add_argument("--headless")
print("Running in headless mode")
else:
print("Running head over hills")
#chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
#define functions
def loginFunction(username, password):
#expects that IDs are existing so need to assign them before calling this function
usernameForm = driver.find_element_by_id('usernameId')
usernameForm.send_keys(username)
passwordForm = driver.find_element_by_id('passwordId')
passwordForm.send_keys(password)
loginButton = driver.find_element_by_id('loginButtonId')
loginButton.click()
print("Logged in successfully!")
def goToTopMenuFunction(MenuName):
topMenuDict = {
"Tools": 5,
"Graphs": 4,
"History": 3,
"Reports": 2,
"Shipments": 1,
"Home": 0,
}
if MenuName in topMenuDict:
print(f"Yes, {MenuName} is one of the keys in the topMenuDict dictionary")
else:
print(f"{MenuName} is not recognized as a top menu option")
menu_number = topMenuDict[MenuName]
print(f"{MenuName} menu is selected")
driver.execute_script(f"""
console.log('0000 --------------------------------------- Go to menu number {menu_number}');
console.log('0001 --------------------------------------- Its name is {MenuName}');
topMenuElements = document.getElementsByClassName('v-menubar-menuitem');
console.log('1111--------------------------------------- '+topMenuElements);
topMenuButton = topMenuElements[{menu_number}];
console.log('1122---------------------------------------- '+topMenuButton);
topMenuButton.style.color = 'red';
topMenuButton.id = '{MenuName}topButton';
console.log(topMenuButton.id);
""")
newButtonId = MenuName + 'topButton';
topMenuButton = driver.find_element_by_id(newButtonId)
print(topMenuButton)
topMenuButton.click()
print(f"{MenuName}menu entered!")
def checkForStackTrace():
if driver.find_elements_by_xpath("//*[contains(text(), 'Given user name is already in use')]"):
print("WARNING LOG:\n User with this name already exists \nWARNING LOG END \n ")
if driver.find_elements_by_xpath("//*[contains(text(), 'RpcInvocationException')]"):
print("ERROR LOG:\n RpcInvocationException \nERROR LOG END \n ")
def goToSubMenuOfTopMenuFunction(SubMenuName):
topSubMenuDict = {
"Server Settings": 0,
"User Profiles": 1,
"Server Log": 2,
"My Settings": 3,
"Locations": 4,
"Integration Endpoints": 5,
"Types": 6,
"Test Data": 7,
"Report fields customization": 8,
"Companies": 9,
"Product types": 10,
}
if SubMenuName in topSubMenuDict:
print(f"Yes, {SubMenuName} is one of the keys in the topMenuDict dictionary")
else:
print(f"{SubMenuName} is not recognized as a top menu option")
sub_menu_number = topSubMenuDict[SubMenuName]
print(f"{SubMenuName} submenu is selected")
driver.execute_script(f"""
subMenuButtonBlockOfOptions = document.getElementsByClassName('v-menubar-submenu-top-menu');
console.log('------------------------------------------ '+subMenuButtonBlockOfOptions);
subMenuButtonBlockOfOptions[0].style.color = 'violet';
subMenuButtonBlockOfOptions[0].id = 'subMenuDropDownDiv';
subMenuDropDownOptions = subMenuButtonBlockOfOptions[0].children;
console.log('-----------------------------------------2 '+subMenuDropDownOptions[0]);
subMenuDropDownOptions[{sub_menu_number}].style.color = 'orange';
subMenuDropDownOptions[{sub_menu_number}].id = '{SubMenuName}Id';
""")
time.sleep(2)
newButtonId = SubMenuName+'Id';
subMenuButton = driver.find_element_by_id(newButtonId)
subMenuButton.click()
print(f"{SubMenuName} menu entered!")
def clickVbuttonFunction(vButtonName):
vButtonDict = {
"Add New User": 2,
"Save": 4,
"Import from CSV": 3,
"Select file":4,
}
if vButtonName in vButtonDict:
print(f"Yes, {vButtonName} is one of the keys in the vButtonDict dictionary")
else:
print(f"{vButtonName} is not recognized as a v-button class member")
v_button_number = vButtonDict[vButtonName]
print(f"{vButtonName} is going to be clicked")
driver.execute_script(f"""
currentVbuttonCandidates = document.getElementsByClassName('v-button');
currentVbuttonCandidates[{v_button_number}].style.backgroundColor = 'blue';
currentVbuttonCandidates[{v_button_number}].style.color = 'red';
//currentVbuttonCandidates[{v_button_number}].style.margin = '50px';
//currentVbuttonCandidates[{v_button_number}].style.padding = '50px';
currentVbuttonCandidates[{v_button_number}].id = '{vButtonName}Id';
""")
time.sleep(3)
newVbuttonId = vButtonName+'Id'
currentVbutton = driver.find_element_by_id(newVbuttonId)
currentVbutton.click()
print(f"{vButtonName} was clicked")
def import_gwtFileUploadFunction(importName):
gwtFileUploadDict = {
"Add New User": 2,
"Save": 4,
"Import from CSV": 3,
"Select file":0,
}
if importName in gwtFileUploadDict:
print(f"Yes, {importName} is one of the keys in the gwtFileUploadDict dictionary")
else:
print(f"{importName} is not recognized as a gwt-FileUpload class member")
importName_number = gwtFileUploadDict[importName]
print(f"Something is going to be imported to {importName}")
driver.execute_script(f"""
currentVbuttonCandidates = document.getElementsByClassName('gwt-FileUpload');
currentVbuttonCandidates[{importName_number}].style.backgroundColor = 'blue';
currentVbuttonCandidates[{importName_number}].style.color = 'red';
//currentVbuttonCandidates[{importName_number}].style.margin = '50px';
//currentVbuttonCandidates[{importName_number}].style.padding = '50px';
currentVbuttonCandidates[{importName_number}].id = '{importName}Id';
""")
time.sleep(3)
importElementId = importName+'Id'
importElement = driver.find_element_by_id(importElementId)
importElement.send_keys("C:\\Users\\username\\Documents\\Projects\\projectName\\products_to_import-ANSI.csv")
print(f"{importName} get some import")
# testprojectNameVVM function actual script starts here
driver.get("http://projectNamestorelinuxdev:4880/projectName/vvm")
driver.set_window_size(1920, 1024)
driver.find_element_by_id('projectname-900094176')
# driver.find_element_by_css_selector('.v-expand')
time.sleep(1)
driver.execute_script("""
div1 = document.getElementById('projectName-900094176');
div1.style.backgroundColor = 'red';
""")
time.sleep(1)
driver.execute_script("""
div1 = document.getElementById('projectName-900094176');
div1.style.backgroundColor = 'red';
div2 = div1.children;
div2[0].style.backgroundColor = 'green';
div3 = div2[0].children;
div3[0].style.backgroundColor = 'yellow';
table1 = document.getElementsByClassName('v-formlayout-margin-top');
array1 = document.getElementsByClassName('v-textfield');
array1[0].style.backgroundColor = 'violet';
array1[0].style.padding = '40px';
array1[0].id = 'usernameId';
array1[1].style.backgroundColor = 'pink';
array1[1].style.padding = '40px';
array1[1].id = 'passwordId';
idCandidates = document.getElementById('gwt-uid-5')
//alert(idCandidates)
//console.log(idCandidates);
div1.style.backgroundColor = 'grey';
button1 = document.getElementsByClassName('v-button');
//console.log('Login button '+button1);
//console.log(' ------------------------------------------ Login button 0'+button1[0]);
button1[0].id = 'loginButtonId';
setTimeout(function() {
console.log('timeout');
}, 2000);
console.log(div2.length);
""")
loginFunction("admin","password")
time.sleep(2)
goToTopMenuFunction("Tools")
time.sleep(2)
goToSubMenuOfTopMenuFunction("User Profiles")
time.sleep(3)
clickVbuttonFunction("Add New User")
time.sleep(2)
driver.execute_script("""
userNamFieldCandidates = document.getElementById('gwt-uid-85');
userNamFieldCandidates.style.color = 'red';
userNamFieldCandidates.style.paddingRight = '150px';
//userNamFieldCandidates[0].id = '';
""")
r1 = random.randrange(10000, 20000)
r1Str = str(r1)
testUserSelenium = 'usrSel' + r1Str
print(f'Trying to create new user with username {testUserSelenium}')
addUserUsername = driver.find_element_by_id('gwt-uid-85')
addUserUsername.send_keys(testUserSelenium)
time.sleep(2)
addUserFirstName = driver.find_element_by_id('gwt-uid-87')
addUserFirstName.send_keys('FirstNameSelenium')
time.sleep(2)
addUserLastName = driver.find_element_by_id('gwt-uid-89')
addUserLastName.send_keys('LastNameSelenium')
time.sleep(2)
addUserPassword = driver.find_element_by_id('gwt-uid-91')
addUserPassword.send_keys('password')
addUserUserTagId = driver.find_element_by_id('gwt-uid-93')
addUserUserTagId.send_keys(r1)
driver.execute_script("""
userGroupSelectBlockCandidates = document.getElementsByClassName('v-select-select');
userGroupSelectBlockCandidates[0].style.color = 'red';
userGroupSelectBlockCandidates[0].style.paddingRight = '150px';
userGroupSelectOptions = userGroupSelectBlockCandidates[0].children;
userGroupSelectOptions[1].style.color = 'blue';
userGroupSelectOptions[1].id = 'userGroupSelectOptionAdminId';
""")
time.sleep(2)
selectUserGroupAdmin = driver.find_element_by_id('userGroupSelectOptionAdminId')
selectUserGroupAdmin.click()
# similar code exists - need to replace with a function if possible
clickVbuttonFunction("Save")
print("Tried to create new user!")
time.sleep(2)
checkForStackTrace()
goToTopMenuFunction("Tools")
time.sleep(1)
goToSubMenuOfTopMenuFunction("Product types")
time.sleep(2)
clickVbuttonFunction("Import from CSV")
time.sleep(2)
import_gwtFileUploadFunction("Select file")
time.sleep(30)
# driver.close()
if (failedToConnect == False):
print('Starting Selenium Test')
testprojectNameVVM(headless)
Selenium + unittest
Selenium WebDriver controls the browser but does not provide a test runner. It is usually paired with a testing library for the language you use.
These examples use Python 3, so common choices include unittest, nose, and pytest.
Selenium bindings are also available for Java, C#, JavaScript, Ruby, and Kotlin.
The example below starts with unittest.
import unittest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import requests
# using time should be probably replaced by some advanced method
import time
chrome_options = Options()
chrome_options.add_argument("--ignore-certificate-errors")
chrome_options.add_argument("--incognito")
# website to be tested url
url = "http://somewebsite.com"
# url = "http://www.google.com/"
# if you need browser to be opened change headless to False
headless = True
#headless = False
# company_specific_div_id
# ID of a page element that should be present when the expected site loads
# Use it to verify that navigation reached the correct page
company_specific_div_id = "someId-12345"
# main page text - to use for successful login assertion
# This text appears on the home page after a successful login.
# Use it to verify that authentication succeeded.
main_page_text = "You have logged in to somewebsite.com"
class TestSomeWebsite(unittest.TestCase):
@classmethod
def setUpClass(inst):
# create a new Chrome session
inst.headless = headless
chrome_options = Options()
if headless == True:
chrome_options.add_argument("--headless")
chrome_options.add_argument("--kiosk")
print("Running in headless mode")
else:
print("Running head over hills")
inst.driver = webdriver.Chrome(options=chrome_options)
inst.driver.implicitly_wait(30)
inst.driver.maximize_window()
# navigate to the application home page
inst.driver.get(url)
inst.driver.title
def test_company_div_exists(self):
self.company_div_to_test = company_specific_div_id
def check_that_div_exists(self,company_div):
self.company_div = company_div
try:
self.driver.find_element_by_id(company_div)
except:
print("\nelement not found")
return False
return True
self.assertTrue(check_that_div_exists(self, self.company_div_to_test))
def test_login(self):
array = self.driver.find_elements_by_class_name("v-textfield")
print(array[0])
array[0].send_keys("userName")
array[1].send_keys("password")
buttons = self.driver.find_elements_by_class_name("v-button")
print(buttons[0])
lbutton = buttons[0]
print(lbutton)
lbutton.click()
def check_that_driver_logged_in(self,text_for_assertion):
self.text_for_assertion = text_for_assertion
try:
homePageText = self.driver.find_element_by_xpath(f"//*[text()='{text_for_assertion}']")
except:
print("\nHH check_that_driver_logged_in function ERROR: Text not found, probably login failed")
return False
return True
self.assertTrue(check_that_driver_logged_in(self,main_page_text), "HH ASSERTION ERROR COMMENT: Text not found")
@classmethod
def tearDownClass(inst):
time.sleep(1)
# close the browser window
inst.driver.quit()
if __name__ == '__main__':
unittest.main()
# Fast select # from selenium.webdriver.support.ui import Select # def fast_multiselect(driver, element_id, labels): # select = Select(driver.find_element_by_id(element_id)) # for label in labels: # select.select_by_visible_text(label)
| Selenium | |
| Basics: WebDriver, selectors and errors | |
| Basic test form | |
| Spider test form | |
| Selenium with Python | |
| Selenium with Java | |
| Software Testing |