Python Selenium and CSS Selectors

In this Python Selenium article we want to learn about Python Selenium and CSS Selectors, so Selenium is an open source framework that enables automated web browser interactions. With Selenium, you can control various web browsers such as Chrome, Firefox, and Safari, Selenium allows you to automate tasks like form submissions, UI testing, data scraping and many more, also Selenium allows you to identify and manipulate elements on a webpage with different method, one of them are CSS Selector that we want to cover in this tutorial.

 

 

Python Selenium CSS Selectors

CSS selectors are patterns that is used to select and target specific HTML elements on a webpage. They are widely used in web development and are equally powerful in web automation. CSS selectors allows you to identify elements based on attributes, classes, IDs, hierarchy and many more. 

 

 

This is the complete code for this article

 

 

 

Now let’s describe above code, first we have imported the necessary modules.

 

 

In here we have created an instance of the Chrome web driver using webdriver.Chrome(). Make sure you have the Chrome driver executable in your system PATH or provide the path to it explicitly, or you can directly add that in your working directory where your Python code exists.

 

 

You can download the drivers from here.

Chrome: https://chromedriver.chromium.org/downloads
Edge: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Firefox: https://github.com/mozilla/geckodriver/releases
Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/

 

 

 

The get() method is used to navigate the web driver to the specified URL, in this case, the login page of the website https://demoqa.com/login, we already have an account with username and password in this website, because we will need that in Python Selenium code.

 

 

 

These lines uses find_element() method to locate the username and password input fields using CSS selectors (“css selector”). The CSS selector #userName selects the element with the ID “userName”, and #password selects the element with the ID “password”. send_keys() method is then used to enter the provided credentials.

 

 

In here, we have used find_element() method with an XPath selector (“xpath”) to locate the login button with the ID “login” (//*[@id=’login’]). click() method is then used to simulate a click on the button, submitting the login form.

 

 

And at the end we use the quit() method to close the browser window and terminate the web driver session.

 

 

 

Learn More on Python Selenium

Leave a Comment