© Sujay Raghavendra 2021
S. RaghavendraPython Testing with Seleniumhttps://doi.org/10.1007/978-1-4842-6249-8_6

6. Buttons

Sujay Raghavendra1 
(1)
Dharwad, Karnataka, India
 

Hyperlink locators used to jump to different sections or pages of a web application were discussed in the previous chapter. The same web locators are used to trace user interface elements like buttons. There are various buttons in a web application, which are described in this chapter.

Buttons are part of the user interface in any web application that interacts with a user/client. These interactions are associated with certain actions, such as moving to the next page and submitting forms. They include default buttons, form/submit button, radio buttons, checkboxes, and select lists. The differences among them depend on the usage, which is explained next.

The types of HTML buttons are located using Python on Selenium because web elements like these buttons have specific functionalities related to them. Let’s start by learning about a default button on a web page.

Default Button

A default button is the most basic type available on an HTML web page. A default button is created using the <button> tag. The following code snippet allows you to create a default button. Figure 6-1 shows the output.
<button id="default_btn" class="default" name="dft_btn" style="font-size:21px;">Default Button</button>
../images/494993_1_En_6_Chapter/494993_1_En_6_Fig1_HTML.jpg
Figure 6-1

Default button

A default button can have various functions, such as edit, delete, create, reset, and clear. Selenium performs two major operations on buttons.
  • Select (locate elements and click)

  • Assert (check for the button and whether enabled/disabled)

Select

Selecting and clicking a button is a way to locate the button element on a web page. A button is activated when clicked, and then it performs the assigned task to it.

Note

The button is always selected by using the click( ) method after locating it on the web page.

There is another method to click a button, which is discussed later in this chapter. A default button can be selected in any of the following ways.

Select by ID

As discussed in earlier chapters, an ID is a unique attribute, and it is used to easily locate a button element.
#Method 1
#Finding or Identifying Default Button
default_button=driver.find_element_by_id('default_btn')
#Clicking on the button selected
default_button.click()
#Method 2
#Identifying & Clicking Default Button
default_button=driver.find_element_by_id('default_btn').click()

The HTML code for the default button in Figure 6-1 is a source to locate the button element. There are two methods for it. In the first method, two functions are used, one for identifying the default button by using an ID, which is then selected by using the click() function (for more information, see Chapter 3).

In the second method, the same functions from the first method are combined in a single line of code. It is utilized in the rest of this chapter. The first method is more readable, whereas the second method is short. It is up to the tester to decide which one to use.

Note

These two methods have the same functionality and purpose.

The ID is stated when the developer is writing the code, which makes it simpler for the tester to use in testing cases.

By Text

This is the most basic selection mechanism for buttons. In this selection type, the default button is selected by using the text written to it, which is seen in the browser.

Figure 6-1 shows the button’s text and its corresponding HTML code. The text always appears on the button when compiled in a browser. In HTML code, the text is placed between the start and end button tags. The following Python Selenium code selects a button by text.
#Using text ()
button_text=driver.find_elements_by_xpath
                        ("//button[text()='Default Button']").click()
The text on a button is also identified using the contain function with the text function.
#Using contain () with text ()
button_text1 =driver.find_elements_by_xpath("//button[contains(text()='Default Button')]").click()

By Name

A button is selected by using the name attribute in HTML when an ID is not available. It is like locating web elements by name, as follows.
default_button=driver.find_element_by_name('dft_btn') .click()

When there are multiple buttons with same name, the first button bearing the name is selected.

Next, let’s look at another type of button.

Submit/Form Button

A submit button submits the data inserted into a form. It is available at the end of the form. The form button is generally created by using the <input> tag or by having submit as a type in the button or input tags. When this button is clicked, it navigates to another page, or a popup message is displayed when used dynamically. Figure 6-2 shows a submit button with its corresponding source code.
<h1> Employee Form</h1>
<form>
  Employee Name:
<input type="text" id="ename" name="ename"><br><br>
  Employee Dept:
<input type="text" id="dept" name="dept"><br><br>
<input type="submit" value="Submit Button">
</form>
../images/494993_1_En_6_Chapter/494993_1_En_6_Fig2_HTML.jpg
Figure 6-2

Submit button

The submit button does not work until all fields are filled, which makes it different from the default button.

Note

The click( ) function for a form button is successful only when all the form elements are filled.

Select by Visible Text

Selecting a submit button is like selecting a default button. Locating these elements is done following the same techniques. The following is a simple example of selecting a submit button by text.
submit_text=driver.find_element_by_xpath
                        ("//input[@value'Submit Button']").click()

XPath is used to locate the submit button by its text, which is case sensitive.

Image as a Button

A button can be created using an image. The image offers a customized look and feel to the user.

To use an image as a button, the input type must be an image with a src attribute defining the path of that image. It is used for both button types. The following is a simple example of a button created using an image.
<form>
<input type="image" id="img" name="img_btn"
                                src="images/go.jpg" alt="Go">
</form>
Figure 6-3 shows an image is used as a button. To select an image button, you use the following Python code in Selenium.
../images/494993_1_En_6_Chapter/494993_1_En_6_Fig3_HTML.jpg
Figure 6-3

Image as a button

#Image Button
image_button=driver.find_element_by_xpath("//input[contains
                                 (@src='images/go.jpg')]")
Note

Images can act as both submit or default types.

Assert for Button

The two main assert approaches for buttons are to verify the presence of a button element on a web page and to check if the element is disabled or not.

The assertion method determines whether the button is present on the given web page. A button can be present on a web page but also be disabled, which makes the button unable to be clicked. The click() function cannot operate on disabled buttons.

Check the Presence of a Button

The presence of a button lets you know whether a button element is available on the specified web page. It is essential to verify whether the specified attribute or path is still available for the button.
#Check if button is enabled or not
if default_button.is_displayed():
        print("Element is Present")
else:
        print("Element Not Present")

Check If the Button Is Enabled or Not

The form button is enabled after a form is completed when dynamically used with JavaScript. There are only rare instances in which a form button is disabled; it may be because the date to submit the form has expired, or only a limited number of forms can be submitted.
#Check if button is enabled or not
if default_button.is_enabled():
        print("Element is Enabled")
else:
        print("Element Not Enabled")

Checking its presence and whether a button is enabled or disabled is done using the if-else condition in Python on Selenium. These validations are the same for all button types.

Next, let’s discussed the radio button, which is one of the most used buttons on a web page that offers choices.

Radio Buttons

Radio buttons are used when multiple choices are available. Each radio button has the same name attribute. When a radio button is selected from a collection, the others are automatically deselected. There is no limit on the number of radio buttons in a group or the number of groups that use radio buttons.

The following is the HTML source code of the radio button shown in Figure 6-4.
<h3>Select your Gender:</h3>
<div>
<input type="radio" id="male" name="gender" value="male"
checked>
<label for="male">Male</label>
</div>
<div>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
</div>
<div>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Prefer not to Say</label>
</div>
../images/494993_1_En_6_Chapter/494993_1_En_6_Fig4_HTML.jpg
Figure 6-4

Radio buttons checked and unchecked

Figure 6-4 shows that when a radio button is selected, a black dot appears in it. There is no dot in the unselected radio buttons. This helps you identify if the radio button was selected/checked or not. Male is checked by default as seen in the HTML source code. Selection is not mandatory in radio buttons.

Note

Selection and checked are referred interchangeably.

The attribute value presents the radio button’s unique value, which is only showcased in the HTML code. The user cannot see it in a browser. The value is transmitted to the server.

Radio buttons have two main operations: to select and to deselect the selected. These two operations are demonstrated next.

Select Radio Buttons

There are various ways to select radio buttons that need to be tested among a group, which are explained as follows.

Simple Select

To select a radio button, you must locate the element and then click it. In this method, the radio button is selected using the ID attribute.
#Selecting female radio button
radio_button=driver.find_element_by_id("female")
radio_button.click()

The ID attribute selected is female, which is associated with the radio button provided in the HTML source. When clicked, a black dot appears in the selected radio button. A dot can be customized into various shapes and colors. The primary motive is to see that the radio button was selected.

Select Using Label

The label is an HTML tag that writes the plain text associated with a form web element. The plain text is written between the start and end tags of the label. This text can also be used to select the radio button.
#Using label attribute with for
radio_button=driver.find_element_by_xpath("//label[@for='female']").click()

The label tag is selected by using XPath and the value of the attribute related to it. The click function is used after locating the radio element.

Note

A black dot in a radio button shows that the button has been selected.

Unselect/Clear Selection

The radio button has two operations associated with it: one is to select, and the other is to deselect. A black dot is available only when a radio button is selected. To clear the selected radio button, you need to select another button because multiple selections are not allowed in the same collection of radio buttons.

The selection of another radio button from the group is made the same way as previous selection types. To avoid the unnecessary selection of radio buttons, a default selection is introduced in some cases.

Note

The only way to deselect an already selected radio button is to select another radio button from the group/collection.

Assert for Radio Button

If there is a group of radio buttons on a web page, to identify if one is checked or to make sure the specified radio element is available on the web page, assertions are used. Assertions play an important role in testing radio buttons and the actions corresponding to them.

Assert If a Radio Button

There are various ways to determine if a web element on a web page is a radio button. A common way is to use the attribute value of the input attribute. If the input type is radio, then the web element is a radio button.
#Locate Web element
radio_button=driver.find_element_by_id("female")
#If stmt to check attribute value
if radio_button.get_attribute("type") =="radio":
                print("It is a Radio button")
else:
                print("It is not a Radio button")

In this example, the web element with female as the ID is checked for its input type using the if statement from the get_attribute( ) function.

Assert If Checked

There are two ways where to assert if a radio button is selected or not. In the first method, the select function is used; it returns a true as the Boolean value if selected and false if not selected. The second method checks the radio button’s attribute value, which is checked in the HTML source. When checked, it returns true; when not checked, it returns false.
#Using Selection function
driver.find_element_by_id("female").is_selected()
#Check using attribute function
driver.find_element_by_id("female").get_attribute("checked")
In some cases, a radio button has a default selection. In Figure 6-3, the default radio button is the first radio element, with male as the text. It can be checked by using the if statement, which returns Boolean values.
radio_button=driver.find_element_by_id("female")
if radio_button.get_attribute("checked") =="true":
                print('Radio Button is "Selected')
else:
                print('Checkbox is Not Selected')

The assertion method checks if the radio button is selected or not. But locating of buttons does not get affected by the type of button to be located using web locators.

Next, let’s examine checkboxes.

Checkbox

Checkboxes have a square box associated with them. They are commonly used when multiple selections are required from the user. There are no restrictions on selecting checkboxes. You could select all the checkboxes in the same group/collection. The selection can also be restricted when necessary, however.

To make a checkbox in HTML, the input type is checkbox. This attribute type lets you know the presence of a checkbox during assertion.
<form>
<input type="checkbox" id="firefox" name="browser1" value=" b1" checked>
<label for="brower1"> Firefox</label><br>
<input type="checkbox" id="chrome" name="browser2" value="b2">
<label for="browser2"> Chrome</label><br>
<input type="checkbox" id="opera" name="browser3" value="b3">
<label for="browser3"> Opera</label><br>
<input type="checkbox" id="edge" name="browser4" value="b4">
<label for="browser4"> Edge</label><br><br>
</form>
Figure 6-5 shows checked and unchecked checkboxes. You know that the checkbox is selected when a tick symbol appears in the square box.
../images/494993_1_En_6_Chapter/494993_1_En_6_Fig5_HTML.jpg
Figure 6-5

Checkbox checked and unchecked

Select/Check

Selecting a checkbox is like selecting a radio button. The difference is that multiple selections are allowed with checkboxes, but radio button selection is limited to one. A checkbox has various attributes associated with it. It is selected by clicking it.

Note

Checkboxes can have multiple selections related to the same group.

Check Using Name

A checkbox can be selected using the name attribute in the HTML source, as follows.
#Select Opera check button
check_button=driver.find_element_by_name("browser3").click()

Check Using ID

In this method, the ID attribute locates the checkbox element and then uses the click function to select it.
#Select Edge check button
check_button=driver.find_element_by_id("edge")
check_button.click()
Note

A tick mark appears when a checkbox has been selected.

Assert If Checkbox

The checkbox attribute type identifies an element as a checkbox, as shown in the following.
#Identify for Checkbox
check_button=driver.find_element_by_id("chrome")
if check_button.get_attribute("type") =="checkbox":
        ˘        print("It is a Checkbox button")
else:
                print("It is not a Checkbox button")

The get attribute function is used in if statement to check for the presence of a checkbox element.

Assert Checkbox If Checked or Not

The ways in which a radio button is checked also apply to a checkbox. The Python Selenium code for checkbox identification on a web page is as follows.
#Using Selection function
driver.find_element_by_id("firefox").is_selected()
#Check using attribute function
driver.find_element_by_id("firefox").get_attribute("checked")

Clear/Unselect/Deselect Checkbox

To remove the tick from a selected checkbox is to deselect, unselect, or clear it. These three terms are used interchangeably. Clearing the textbox is allowed in Python on Selenium, and it is used to test that the checkbox is working correctly. In some cases, the checkbox is disabled or is set to default, which does not allow you to clear it.

A checkbox must be selected before clearing it. This is done by using the same click() function again. To determine if a checkbox is selected or not, you can use the assert function.
#Clearing checkbox
check_button=driver.find_element_by_id('firefox')
#if condition to check selection
if check_button.is_selected():
        #Clear using click()
        check_button.click()
        print('Checkbox clicked to deselected')
else:
        print('Checkbox is not selected')

In this code, the checkbox is recognized if it has already been selected using the if condition statement; if selected, then it is cleared or unselected.

Note

Clearing the checkbox can be done only when it is selected.

All the methods used in checkboxes are the same ones available for radio buttons, apart from the clearing method. A radio button automatically clears after selecting another option. This is not the case with a checkbox; hence, clear/deselect is done by performing the same action used to select.

Next, let’s discuss the select list.

Select List

The final button type is the select list. This button type can act as both a radio button or a checkbox when the user can select a single choice or multiple choice. A select list creates multiple options listed in a drop-down list. One or multiple options can be selected from the list. A select list is formed by combining the <select> and <option> tags, respectively. It is similar to a drop-down menu.
<h1>Blood Group</h1>
<label for="blood">Choose Blood Group:</label>
<select name = "blood" id = "bld_grp">
<option value = "A"> A type </ option>
<option value = "B"> B type </ option>
<option value = "O"> O type </ option>
<option value = "AB"> AB type </ option>
<option value = "Bombay"> Bombay type </ option>
</select>

Select lists are commonly used inside a form tag but can be used independently. The number of options that can be selected from the lists can be controlled. When only one option can be selected from a list, it behaves as a radio button. When multiple options can be selected from a list, it acts as a checkbox.

Figures 6-6 and 6-7 show a drop-down menu that lists five human blood types. The drop-down menu is opened by clicking it, which allows you to choose from it as well.
../images/494993_1_En_6_Chapter/494993_1_En_6_Fig6_HTML.jpg
Figure 6-6

Single select list

../images/494993_1_En_6_Chapter/494993_1_En_6_Fig7_HTML.jpg
Figure 6-7

Open select list

Getting All the Options

You need to know all the options available in a list. This is done by using the following code.
s = driver.find_elements_by_tag_name("option")
for option in s:
    print("Option is: %s" % option.get_attribute("value"))

As stated in the code, the for loop returns all the options in the blood group select list.

Select

Python in Selenium provides many ways to select from the available options. Before selecting the select list from the web page/app, you need to import the select library from selenium.webdriver.support.select in Python. The selection methods are discussed next.

Select Using Visible Text

The text that is visible in a drop-down list can be used as a medium to select the options.
#Importing Select Library
from selenium.webdriver.support.select import Select
# First Select ID of drop-down
select_list=Select(driver.find_element_by_id('bld_grp'))
# select by visible text
select_list.select_by_visible_text('O type')

In the selection process of a drop-down/select list, the drop-down menu is located first. Then, an instance is created to select an option from the list. The drop-down can be located using several attributes, such as ID and name.

Select by Value

The value attribute associated with each option is different. These attribute values select the option. The available values in the select list are A, B, O, AB, and Bombay.
# Select drop-down ID
select_list=Select(driver.find_element_by_name('blood'))
# Select by visible text
select_list.select_by_value('O')

The value attributes are case sensitive and allow alphanumeric characters.

The O blood type needs to be selected. This is done by first selecting the drop-down in which the option is located, and then the instance is created to select the specified option.

Select Using Index

The options in the select list have index values that are not specified in the HTML code. Selenium allows you to select an option using these index values. The index value starts at 0 and is related to the first option in the select list.
# Selecting Drop-down
select_list=Select(driver.find_element_by_id('bld_grp'))
# Selecting last option Bombay by index value
select_list.select_by_index('4')

An index value of 4 selects the last option in the drop-down list. To select options using an index value, you need to know the number of available options in the drop-down.

To select the last option in the drop-down list, use a –1 index value, which is commonly used in Python.
# Selecting last option Bombay by index value
select_list.select_by_index('-1')
Note

The select method in Python on Selenium cannot be used if the list was not built using the select tag.

Unselect/Clear/Deselect

The options selected from a list can revert by clearing it. Unselecting/deselecting/clearing (the terms are synonymous) an option in a select list can be done the same way the selection was made. The list may allow single or multiple selections.

Deselect/Clear One Selected

Deselection can be made to single or multiple options in the list. The following discusses deselecting/clearing a single option.

Deselect by Visible Text

The text that is visible in a list can be accepted as a value to deselect it when selected.
#clear using index
clear= Select(driver.find_element_by_id('bld_grp'))
clear.deselect_by_index('Bombay')

The last option, Bombay, is deselected using a visible text function.

Deselect by Value

When a specified value matches the value attribute in the list, that list element is deselected.
#clear by value
clear= Select(driver.find_element_by_id('bld_grp'))
clear.deselect_by_value ('O')

There are two possible exceptions may be raised in this case, one when there is no match for the defined value. The second exception is raised after the value is matched but the list element is not selected as deselect works only if list is selected.

Deselect by Index

An option in a list is deselected using its index value. Similar to selecting an option with the index value, an option can also be cleared/deselected.
#clear by index
clear= Select(driver.find_element_by_id('bld_grp'))
clear.deselect_by_index('4')

The last element in the list is cleared if selected; otherwise, an exception is raised.

Multiple Select List

A select list may allow multiple options to be selected. The HTML source and its corresponding output are shown in Figure 6-8. In multiple selections, there are seven options available and among them four have been selected. The code for selecting these options are made as follows. all_options cannot be used as it selects all available list.
<h1>Fruit Salad</h1>
<label for="fruits">Choose Multiple Fruits:</label>
<select id="fruits" name="fruits" size="7" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cranberry">Cranberry</option>
<option value="dragonfruit">Dragon Fruit</option>
<option value="elderberry">Elderberry</option>
<option value="figs">Figs Fruit</option>
<option value="grapes"> Grapes</option>
</select>
<br><br>
<p>For Windows, hold the Ctrl button while selecting options. For Mac, hold the Command button while selecting options.</p>
../images/494993_1_En_6_Chapter/494993_1_En_6_Fig8_HTML.jpg
Figure 6-8

Multiple select list

In multiple selections, there are seven options available, and out of them, four have been selected. The selections are made as follows in the code.
ticks = Select(driver.find_element_by_id('fruits'))
#Selecting Options in different ways
ticks.select_by_index(0)
ticks.select_by_value ('cranberry')
ticks.select_by_visible_text('Elderberry')
ticks.select_by_index(6)

Verify

Assertion functions are used to avoid exceptions that arise in an element not found, or when the element needs to be deselected when not selected and vice versa. These kinds of exceptions can be avoided using option functions that let you know the type of list and whether it is selected or not.

Get the First Option Selected

The first option that is selected in a multiple select list or the current selected option in a single select list is returned.
selected_list=Select(driver.find_element_by_id('bld_grp'))
#Prints first selected option value
print (selected_list.first_selected_option.get_attribute('value'))

The print statement prints the first selected option from the list and returns an error if no option is selected.

Get All Options Selected

To get all selected options from the list, a function named all_selected_options() is used.
selected_list=Select(driver.find_element_by_id('bld_grp'))
#Returns all selected options
selected_list.all_selected_options()

It is mainly used in a multiple select list that returns all selected options.

Deselect/Clear All Selected

This function clears/deselects all the selected options from the drop-down list. It is mainly used with multiple selections in a list. When no multiple selections are available, a NotImplementError exception is raised.
#Clear all selected
clear= Select(driver.find_element_by_id('bld_grp'))
clear.deselect_all()

To clear all the selected options in a list, Selenium provides the deselect_all() function .

Note

The select method in Python on Selenium cannot be used if the list is not built using the select tag.

Summary

This chapter explains the mouse/keyboard actions and web locators discussed in Chapters 3 and 4 that are most often used on a user interface (i.e., the buttons in a web application). The web locators find all types of buttons available, and corresponding actions are performed on them.

The default button, when located, is only allowed to perform click action. The Submit button is used for forms. The radio button provides multiple choices but allows only one selection among them. Checkboxes allow multiple choices and selections. A select list is a button further classified into two types based on the single or multiple selections in it. Each button was illustrated with an example.

Locating UI web elements like frames and textboxes are discussed in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181