Introduction to Selenium:-
Selenium is a portable framework for web application testing that was created by Jason Huggins in 2004. It gives you the tools you need to write practical tests without having to learn a scripting language. It also includes the Selenese domain-specific language, which can be used to write tests in Scala, Ruby, Python, PHP, Perl, Java, Groovy, C#, and other common programming languages. Most modern web browsers, such as Google Chrome, Mozilla Firefox, Internet Explorer, Edge, Opera, Safari, and others, will run Selenium tests. It also works with a variety of operating systems, including Windows, Linux, and macOS. It is free and open-source software licensed under the Apache License 2.0.
Selenium IDE: The Selenium Suite's key tool is the Selenium IDE. It is the simplest and most straightforward framework in the Selenium suite. It's available as a Chrome Extension and a Firefox Add-On. It's a web automation research platform that's free to use. Unlike Selenium WebDriver and RC, it does not require any programming logic to write test scripts.
Selenium RC: Selenium Remote Control (RC) is a Java-based server that accepts browser HTTP commands. In any programming language, RC assists us in writing automated tests for a web application.
Selenium WebDriver: Selenium Webdriver is a collection of APIs for testing web applications that are available for free. The Selenium Webdriver tool is used to automate web application testing to ensure that it functions properly.
Selenium Grid: Selenium Grid is a Selenium Suite component that allows you to run multiple tests simultaneously across multiple browsers, operating systems, and computers.
NOTE: We have used Python as our programming language in the examples below.
Importing the Selenium Webdriver:-
from selenium import webdriver
Starting the Webdriver and browser : -
Chrome Browser :-
chromedriver = "C:/tests/chromedriver.exe"
driver = webdriver.Chrome(executable_path = chromedriver)
Firefox Browser:-
geckodriver = "C:/tests/geckodriver.exe"
driver = webdriver.Firefox(executable_path = geckodriver)
Internet Explorer Browser :-
iedriver = "C:/tests/IEDriverServer.exe"
driver = webdriver.Firefox(executable_path = iedriver)
Safari Browser:-
driver = webdriver.Safari()
Setting Desired Capabilities of the browser:-
Browser Arguments:-
Example :-
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless")
options.add_argument("--start-maximized")
options.add_argument("--disable-notifications")
options.add_argument("--incognito")
driver = webdriver.Chrome(chrome_options=options, executable_path="C:/tests/chromedriver.exe")
Opening a Website :-
url = "https://www.google.com"
driver.get(url)
Finding an element:-
Let us consider the element to be found is as follows :-
<a href="/login" id="login" name="login" class="class1">Login to your account</a>
Finding by ID :-
the_id = 'login'
element = driver.find_element_by_id(the_id)
Finding by name:-
name = 'login'
element = driver.find_element_by_id(name)
Finding by class name:-
className = 'class1'
element = driver.find_element_by_class_name(className)
Finding by Tag name:-
tagName = 'a'
element = driver.find_element_by_tag_name(tagName)
Finding element by Link text:-
linkText = 'Login to your account'
element = driver.find_element_by_link_text(linkText)
Finding element by Partial Link Text:-
partialLinkText = 'Login'
element = driver.find_element_by_partial_link_text(partialLinkText)
Finding element by CSS selector:-
We can either extract the CSS selector from the browser or we can simply create our own by using an attribute from the element.
*[ attribute = "Value" ]
For our considered example, a custom selector could be
a[ href = "/login" ]
cssSelector = 'a[href="/login"]'
element = driver.find_element_by_css_selector(cssSelector)
Finding an element by XPath:-
We can either extract the XPath from the browser or we can create our own using an attribute from the element.
//*[@attribute = "Value"]
For our considered example, a custom XPath could be result aj hi aaega na
//a[@href = "/login"]`
xPath = '//a[@href = "/login"]'
element = driver.find_element_by_xpath(xPath)
Clicking on an element:-
idName = 'login'
element = driver.find_element_by_id(idName)
element.click()
Writing text inside an element:-
idName = 'email'
emailAddress = 'sample@interviewbit.com'
element = driver.find_element_by_id(idName)
element.send_keys(emailAddress)
Selecting an option:-
Let us consider an example :-
<select id="fruits">
<option value="Red">Apple</option>
<option value="Orange">Papaya</option>
<option value="Yellow">Banana</option>
</select>
For selecting Apple, from the above options we will use :-
idName = 'fruits'
element = driver.find_element_by_id(idName)
selectedElements = Select(element)
selectedElements.select_by_visible_text('Apple')
We can also use the value for selecting :-
idName = 'fruits'
element = driver.find_element_by_id(idName)
selectedElement = Select(element)
selectedElement.select_by_value('Red')
We can also use the index as follows:-
idName = 'fruits'
element = driver.find_element_by_id(idName)
selectedElement = Select(element)
selectedElement.select_by_index(1)
Taking a Screenshot:-
pathName = 'C:/tests/screenshots/sample.png'
driver.save_screenshot(pathName)
Uploading a file:-
Let us consider an example with the following input button :-
<input type="file" multiple="" id="uploadButton">
filePath = 'C:/tests/files/sample.pdf'
idName = 'uploadButton'
element = driver.find_element_by_id(idName)
element.send_keys(filePath)
Executing a Javascript code:-
jsCode = 'document.getElementById("id1").remove()'
driver = execute_script(jsCode)
Switching to the next tab:-
We need to store the handle of the current tab in a global variable. If the number of open tabs is one, the handle is zero.
global nextTab
global currentTab
nextTab = currentTab + 1
driver.switch_to_window(driver.window_handles[nextTab])
currentTab = currentTab + 1
Switching to the previous tab:-
global previousTab
global currentTab
previousTab = currentTab - 1
driver.switch_to_window(driver.window_handles[previousTab])
currentTab = currentTab - 1
Switching to iframe:-
<iframe id="details_section">
<input id="MobileNumber">
<input id="EmailID">
<input id="DOB">
</iframe>
iframeID = 'details_section'
elementID = 'MobileNumber'
foundiFrame = driver.find_element_by_id(iframeID)
driver.switch_to.frame(foundiFrame)
element = driver.find_element_by_id(elementID)
element.send_keys('912345678')
driver.switch_to.default_content()
Closing a tab:-
driver.close()
Closing an alert:-
driver.switch_to.alert.accept()
Refreshing the web page :-
driver.refresh()
Hovering:-
idName = "login"
element = driver.find_element_by_id(idName)
hover = ActionChains(driver).move_to_element(element)
hover.perform()
To perform right click:-
idName = "login"
element = driver.find_element_by_id(idName)
right_click = ActionChains(driver).context_click(element)
right_click.perform()
To press key:-
idName = 'login'
element = driver.find_element_by_id(idName)
element.send_keys(Keys.RETURN)
To drag and drop:-
idDrag = 'source'
idTarget = 'target'
dragElement = driver.find_element_by_id(idDrag)
targetElement = driver.find_element_by_id(idTarget)
ActionChains(driver).drag_and_drop(idDrag, targetElement).perform()
To get the page source:-
pageSource = driver.page_source
To get the cookies:-
cookies_list = driver.get_cookies()
To delete cookies:-
cookie_item = 'cookieName'
# To delete one cookie
driver.delete_cookie(cookie_item)
# To delete all cookies
driver.delete_all_cookies()
To get the first element from the list:-
idName = 'login'
list_of_elements = driver.find_elements_by_id(idName)
firstElement = list_of_elements[0]
To set the window size:-
driver.set_window_size(1200, 800)
To add a chrome extension:-
chromedriver = 'C:/tests/chromedriver.exe'
extension_path = 'C:/tests/sampleExtension.zip'
options = webdriver.ChromeOptions()
options.add_extension(extension_path)
driver = webdriver.Chrome(
executable_path = chromedriver,
chrome_options = options)
To simulate webcam and microphone:-
chromedriver = 'C:/tests/chromedriver.exe'
options = webdriver.ChromeOptions()
options.add_argument("--use-fake-ui-for-media-stream")
options.add_argument("--use-fake-device-for-media-stream")
driver = webdriver.Chrome(
executable_path = chromedriver,
chrome_options = options)
To configure the page load timeout:-
driver.set_page_load_timeout(10)
To configure element load timeout:-
from selenium.webdriver.support.ui import WebDriverWait
idName = 'login'
WebDriverWait(driver,15).until(EC.presence_of_element_located((By.ID, idName)))
To click with offset:-
We must provide the offset in order to precisely click on a specific position in a canvas feature. Starting from the top left corner of your canvas part, the offset represents the number of pixels to the right and down.
idName = "login"
element = driver.find_element_by_id(idName)
x = 20
y = 15
offset = ActionChains(driver).move_to_element_with_offset(element,x,y)
offset.click()
offset.perform()
To emulate mobile device:-
userAgent = 'Mozilla/5.0 (Linux; Android 9.0; Pixel 3 XL Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.98 Mobile Safari/537.36'
emulationOfMobile = {
"deviceMetrics": {
"width": 411,
"height": 731,
"pixelRatio": 3
},
"userAgent": userAgent
}
options = webdriver.ChromeOptions()
options.add_experimental_option("mobileEmulation", emulationOfMobile)
driver = webdriver.Chrome(
executable_path = chromedriver,
chrome_options = options)
Conclusion:-
On the market, Selenium testers are in high demand. Since Selenium is becoming more common, the demand for Selenium testers is also growing. Testing repeated test scenarios on each and every new build takes almost no time at all with Selenium. As a consequence, the workload of the tester is reduced. It enables the tester to operate on several test scenarios at once. Due to machine overhead (performance) or lack of functionality, other methods do not have the luxury of parallel and distributed testing, which can be a major factor in persuading you to learn Selenium.
Readers can always go through the official documentation of Selenium if they get stuck somewhere. Here's the link to it:- https://www.selenium.dev/documentation/en/.