Python Selenium
About Lesson

In this Python Selenium tutorial we are going to learn about Python Selenium Web Elements, we will have a simple introduction to Web Elements in Selenium, how you can interact with web elements in python selenium and how you can use different locators like id, name and xpath.

 

 

What are Web Element in Selenium ?

A web page is created of many different HTML elements, such as buttons,  links, a body, labels, forms, and so on, that are named WebElements in the context of WebDriver. Together, these elements on a web page will achieve the business functionality. For example, let’s look at the HTML code of the login page of a website.

 

You can see in the above code that our login.html file is created by different web elements, for example we have text input fields for entering our password and username, also we have a button for submitting the form. and also you can see that for these web elements we have attributes, for example for input fields we have name attribute. UI Automation in Selenium is mostly about locating these WebElements on a web page and  executing user actions on them. and there are different ways that you can locate a web element in a web page, for example you can use id, name, tag, xpath, that we will use some of them in this article.

 

 

 

Locating Web Elements 

OK now let’s start our example by automating Google Search page, which we want opening of the Google Search page, locating the search input field, typing something and searching for that.

 

In the above example we are going to use the name locator of web elements, first of all we have imported the required classes, and after that we have opened our chrome browser and finding Google website.

 

 

As i have already said that there are different ways that you can interact with the selenium web elements, in here we have used the name locator of google search field.

 

 

After that we are sending the python key to the Google Search input field, and at the end we are searching that. also we have added a time sleep.

 

 

 

Run the code and this is the result.

Python Selenium Web Elements
Python Selenium Web Elements

 

 

 

Web Element Locator by XPath

There are may be situations, that you will not have the name attribute for the web element, on that time you can use XPath. just inspect the element in Chrome and after that right click and choose copy XPath.

Python Selenium XPath
Python Selenium XPath

 

 

 

And this is the code for the XPath.

We have just used find_element_by_xpath() method.

 

 

 

Web Element Locator By Name

Also you can use name attribute for finding web element locators. and for that you can use find_element_by_name() method.