<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Vinayak Sharma</title>
    <description>The latest articles on Forem by Vinayak Sharma (@vinayaksharma123).</description>
    <link>https://forem.com/vinayaksharma123</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F922537%2Fbaa0b695-2939-4331-b9a3-c47184bb97de.jpeg</url>
      <title>Forem: Vinayak Sharma</title>
      <link>https://forem.com/vinayaksharma123</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/vinayaksharma123"/>
    <language>en</language>
    <item>
      <title>Selenium with Python Tutorial: Creating Automated Web Bot</title>
      <dc:creator>Vinayak Sharma</dc:creator>
      <pubDate>Wed, 21 Sep 2022 14:59:40 +0000</pubDate>
      <link>https://forem.com/testmuai/selenium-with-python-tutorial-creating-automated-web-bot-20f5</link>
      <guid>https://forem.com/testmuai/selenium-with-python-tutorial-creating-automated-web-bot-20f5</guid>
      <description>&lt;p&gt;Selenium is one of the preferred test automation frameworks, primarily used for &lt;a href="https://www.lambdatest.com/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;web automation testing&lt;/a&gt;. Though Selenium supports six popular programming languages, it can be used to weave magic with lesser implementation when used with Python such as creating web bot using Selenium with Python.&lt;/p&gt;

&lt;p&gt;Beyond web automation testing, &lt;a href="https://www.lambdatest.com/blog/web-scraping-using-selenium-and-python/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;web scraping using Selenium Python&lt;/a&gt; is a very popular use case that you can do with fewer LOC with Python. As a QA engineer, I still use other programming languages like Java and JavaScript with Selenium, but Python has been my go-to language for simple/complex web automation tasks like is this tutorial for web bots using selenium with python.&lt;/p&gt;

&lt;p&gt;As mentioned in this &lt;a href="https://www.lambdatest.com/blog/selenium-webdriver-with-python/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Selenium Python tutorial&lt;/a&gt;, Python is the third-most-popular programming language after HTML/CSS and JavaScript. Web bot using Selenium with Python or Selenium Python bot can be used extensively for automating multiple scenarios (or tasks).&lt;/p&gt;

&lt;p&gt;In this Selenium Python tutorial on Selenium Python bot, I deep dive into how to create a web bot in Selenium and Python; the learnings of which will be useful for multiple aspects of Selenium automation testing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tools For Creating Web Bot using Selenium with Python
&lt;/h2&gt;

&lt;p&gt;One of the primary objectives of creating a Selenium with Python bot is to leverage the capabilities offered by Selenium for automating interactions with WebElements in the DOM. There is a suite of Selenium testing tools for automating web browsers, which can be used for a range of automation tasks like web scraping, web automation testing, cross browser testing, and much more.&lt;/p&gt;

&lt;p&gt;So, let’s look at the setup essentials that are required for creating a web bot using Selenium with Python.&lt;/p&gt;

&lt;h2&gt;
  
  
  Selenium
&lt;/h2&gt;

&lt;p&gt;The Python library that wraps the Selenium WebDriver provides binding and a simple API to write functional tests for automating web tasks such as clicking buttons, navigating web pages, and filling out forms.&lt;/p&gt;

&lt;p&gt;The test script does not interact directly with the web browser. Selenium WebDriver is the core of the Selenium framework. As mentioned in this &lt;a href="https://www.lambdatest.com/blog/selenium-webdriver-tutorial-for-cross-browser-testing/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Selenium WebDriver tutorial&lt;/a&gt;, Selenium WebDriver is instrumental in establishing the connection with the browser using its corresponding browser driver. However, you can further deep dive into what is Selenium, if you want to know more about Selenium and its components.&lt;/p&gt;

&lt;p&gt;If the tests have to be run on a local Selenium grid, the corresponding browser driver has to be installed on the target machine:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AK3TldsNPLuXhcSj3higGHg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AK3TldsNPLuXhcSj3higGHg.png" width="800" height="299"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Downloading and installing the browser drivers are required only when the tests have to be performed on the local Selenium Grid. In the case of a Remote Selenium WebDriver, the tests are executed on a cloud Selenium Grid (e.g. LambdaTest).&lt;/p&gt;

&lt;h2&gt;
  
  
  Python Automation Frameworks
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.lambdatest.com/blog/python-automation-testing/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Python for Selenium Automation Testing&lt;/a&gt; is a preferable choice since the language is less verbose, supports dynamic typing, supports hassle-free reporting, and much more. The wide range of Selenium with Python frameworks support parallel testing in Selenium; thereby expediting the time to market. Also, creating a Web Bot using Selenium with python is a very Simple and easy-to-implement process.&lt;/p&gt;

&lt;p&gt;In this Selenium with Python tutorial, I have touched upon the essentials of Selenium with Python, let’s me, deep dive, into the most popular Selenium with Python frameworks for automation testing:&lt;/p&gt;

&lt;h3&gt;
  
  
  PyUnit (Unittest)
&lt;/h3&gt;

&lt;p&gt;Unittest (or PyUnit) is the default Python testing framework that comes with the Python package. This testing framework for Python is inspired by the popular JUnit framework. Creating a Web Bot using Selenium with Python Can be achieved with Unittest framework.&lt;/p&gt;

&lt;p&gt;Unittest provides simple and flexible test case execution with the quick generation of test reports. Unittest uses camelCase naming conventions instead of Python’s snake_case naming conventions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.lambdatest.com/blog/using-pyunit-for-testing-a-selenium-python-test-suite/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Selenium PyUnit tutorial&lt;/a&gt; can be a good starting point for someone looking to leverage the framework for web automation testing.&lt;/p&gt;

&lt;h3&gt;
  
  
  PyTest
&lt;/h3&gt;

&lt;p&gt;PyTest is an open-source testing framework that supports unit testing, functional testing, and API testing. It is available on Python version 3.5 (and higher). Making a Web Bot using Selenium with Python Can be accomplished with PyTest.&lt;/p&gt;

&lt;p&gt;Page Object Model (POM) in Selenium Python is instrumental in improving the maintainability and reusability aspects of the source code. I prefer the PyTest framework over PyUnit due to the rich set of plugins that are a boon to the automation engineers.&lt;/p&gt;

&lt;p&gt;Some of the most popular PyTest plugins for automation engineers are below:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;pytest-randomly&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;pytest-cov&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;pytest-django&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;pytest-bdd&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Selenium PyTest tutorial deep dives into all the integral aspects of web automation testing with Selenium and PyTest.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/UzkuOACmBpA"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;This PyTest Tutorial for beginners and professionals will help you learn how to use the PyTest framework with Selenium and Python for performing Selenium automation testing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Learn what &lt;a href="https://www.lambdatest.com/selenium?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;Selenium&lt;/a&gt; is and its benefits for automated cross browser testing. See how Selenium works and get ready to use it for testing. Read more.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Robot Framework
&lt;/h3&gt;

&lt;p&gt;The Robot Framework is an open-source automation framework that allows the creation of human-readable test cases using Gherkin.&lt;/p&gt;

&lt;p&gt;Watch this video to learn the basics of the robot framework for automation testing. This video will give you an understanding of the various functionalities of the Robot Framework with live examples. Developers and testers mainly use Robot Framework to make a Web Bot using Selenium with Python as it as various functionalities.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/yf8AJqUc5Uo"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;p&gt;The Robot framework is best suited to leverage the benefits of &lt;a href="https://www.lambdatest.com/blog/behaviour-driven-development-by-selenium-testing-with-gherkin/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Behaviour Driven Development (BDD) using Selenium and Gherkin&lt;/a&gt;. Robot is also used for acceptance of Test-Driven Development (TDD) and Robotic Process Automation (RPA).&lt;/p&gt;

&lt;p&gt;The core implementation of Robot Framework is in Python but can also run on Jython and IronPython. It natively doesn’t support parallel testing but provides a variety of extensions and libraries which are easy to use.&lt;/p&gt;

&lt;p&gt;For demonstrating the implementation of the Selenium Python bot, I am going to use the PyTest framework.&lt;/p&gt;

&lt;h3&gt;
  
  
  Behave
&lt;/h3&gt;

&lt;p&gt;Behave is testing frameworks used for Behavior-Driven Development (BDD). It has a large amount of documentation and support from the community. To top it all, it provides inbuilt integrations of Django and Flask — two of the most popular web frameworks in Python. After Robot framework Behave to make a Web Bot using Selenium with Python.&lt;/p&gt;

&lt;p&gt;Behave is also useful for black box testing. BDD with Behave and Selenium comes with its own set of advantages &amp;amp; shortcomings but it is still a nifty Python automation testing framework for Selenium testing.&lt;/p&gt;

&lt;p&gt;Apart from these frameworks that I normally use for web automation testing, there are a number of popular Selenium Python frameworks that can be looked into to leverage the capabilities of Selenium and Python.&lt;/p&gt;

&lt;h2&gt;
  
  
  Task Schedulers in Python
&lt;/h2&gt;

&lt;p&gt;Task Schedulers are programs that enable scheduling of tasks or scripts after certain time intervals. Alternately, scripts can also be scheduled (or triggered) based on certain conditions.&lt;/p&gt;

&lt;p&gt;Task Scheduler can be used extensively for running a batch (or .bat) file that triggers the corresponding Python script.&lt;/p&gt;

&lt;p&gt;Some of the common programs that provide task scheduling in Python are:&lt;/p&gt;

&lt;h3&gt;
  
  
  Cron
&lt;/h3&gt;

&lt;p&gt;Cron is a time-based job scheduler in Unix-like computer operating systems such as Linux and macOS. It allows users to schedule tasks such as taking backups, create logs, and run scripts&lt;/p&gt;

&lt;h3&gt;
  
  
  Windows Task Scheduler
&lt;/h3&gt;

&lt;p&gt;Task Scheduler is a component of Windows OS that lets you create and run essentially any task in an automatic fashion. Usually, the system and certain apps are scheduled for automation and maintenance. Tasks like disk defragmentation, disk cleanup, and updates, etc. can be scheduled automatically using the Windows Task Scheduler.&lt;/p&gt;

&lt;p&gt;Windows Task Scheduler works by keeping track of the time and events on the computers and executes the task if the necessary conditions are met.&lt;/p&gt;

&lt;p&gt;For this blog, I am going to use the Windows Task Scheduler program, along with the Win32com Library — a thin Python wrapper that helps automate Windows applications. In this case, it’s the Task Scheduler.&lt;/p&gt;

&lt;p&gt;Now that we have touched upon the integral aspects of building a web bot using Selenium with Python, let’s get our hands dirty with some implementation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Execute &lt;a href="https://www.lambdatest.com/playwright-testing?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;Playwright&lt;/a&gt; testing in parallel and cut down your test execution time by multiple folds.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Building Automated Web Bot using Selenium with Python
&lt;/h2&gt;

&lt;p&gt;Follow the below mentioned steps to create a development environment for the implementation:&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating a Virtual environment and installing dependencies
&lt;/h2&gt;

&lt;p&gt;Virtual environment (or virtualenv) is a tool for creating isolated Python environments. For this purpose, Python provides a venv module that supports creation of lightweight “virtual environments” with its isolated site directories.&lt;/p&gt;

&lt;p&gt;You can check out this &lt;a href="https://www.lambdatest.com/blog/getting-started-with-selenium-python/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Selenium Python&lt;/a&gt; tutorial for a quick refresher on web automation testing with Selenium and Python.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python3 -m venv env
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ol&gt;
&lt;li&gt;Run the below mentioned command to activate this virtual environment:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Windows&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.\env\Scripts\activate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Linux&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;source env/bin/activate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Run the following command to install Selenium for Python:&lt;/p&gt;

&lt;p&gt;pip install selenium&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Run the following command to install the PyTest framework:&lt;/p&gt;

&lt;p&gt;pip install pytest&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Install the pywin32 package to for managing the Windows Task Scheduler:&lt;/p&gt;

&lt;p&gt;pip install pywin32&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Folder structure of Test Scripts
&lt;/h2&gt;

&lt;p&gt;The project majorly consists of two files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;main.py&lt;/strong&gt; — Contains the main script that enables logging on to the LambdaTest platform and fetching details of the respective tests.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;scheduler.py&lt;/strong&gt; — Contains the implementation to schedule the test scripts.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A9h9skk5CgshnEboE2uqrMw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A9h9skk5CgshnEboE2uqrMw.png" width="530" height="152"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;A comprehensive &lt;a href="https://www.lambdatest.com/learning-hub/end-to-end-testing?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=learning_hub" rel="noopener noreferrer"&gt;end to end Testing&lt;/a&gt; tutorial that covers what E2E Testing is, its importance, benefits, and how to perform it with real-time examples.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementation of Automated Selenium Python bot
&lt;/h2&gt;

&lt;p&gt;For demonstrating the creation of Web Bot using Selenium with Python, we automate the test scenario of logging on to the LambdaTest platform. The URL under test is &lt;a href="https://accounts.lambdatest.com/login" rel="noopener noreferrer"&gt;https://accounts.lambdatest.com/login&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Since the test is demonstrated on the LambdaTest Grid, I am using the Remote WebDriver in Selenium instead of the local WebDriver. To get started, we import the necessary packages.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We define two variables that point to the username and access key, the combination of which is used for accessing the LambdaTest cloud grid. The username and access key can be accessed from LambdaTest profile page.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;username = "&amp;lt;YOUR USERNAME&amp;gt;"
access_key = "&amp;lt;YOUR ACCESS KEY&amp;gt;"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Define a class named ‘TestClass’ with the following functions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Setup_method&lt;/strong&gt; — It is a function used for setting up the remote driver and its corresponding properties.&lt;/p&gt;
&lt;h1&gt;
  
  
  Generate capabilities from here: &lt;a href="https://www.lambdatest.com/capabilities-generator/" rel="noopener noreferrer"&gt;https://www.lambdatest.com/capabilities-generator/&lt;/a&gt;
&lt;/h1&gt;
&lt;h1&gt;
  
  
  setUp runs before each test case and
&lt;/h1&gt;

&lt;p&gt;def setup_method(self):&lt;br&gt;
desired_caps = {&lt;br&gt;
       "build": "your build name",&lt;br&gt;
       "name": "your test name",&lt;br&gt;
       "platform": "Windows 10",&lt;br&gt;
       "browserName": "Chrome",&lt;br&gt;
       "version": "92.0",&lt;br&gt;
       "selenium_version": "3.13.0",&lt;br&gt;
       "geoLocation": "IN",&lt;br&gt;
       "chrome.driver": "91.0",&lt;br&gt;
}&lt;br&gt;
"""&lt;br&gt;
Setup remote driver&lt;br&gt;
       -------&lt;br&gt;
       username and access_key can be found on the lambdatest platform&lt;/p&gt;

&lt;p&gt;"""&lt;br&gt;
self.driver = webdriver.Remote(&lt;br&gt;
       command_executor="&lt;a href="https://{}:{}&amp;lt;a%20href=" rel="noopener noreferrer"&gt;@hub&lt;/a&gt;.lambdatest.com/wd/hub"&amp;gt;https://{}:{}&lt;a href="http://twitter.com/hub" rel="noopener noreferrer"&gt;@hub&lt;/a&gt;.lambdatest.com/wd/hub".format(&lt;br&gt;
       username, access_key&lt;br&gt;
       ),&lt;br&gt;
       desired_capabilities=desired_caps )&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Teardown_method&lt;/strong&gt; — It is a function used for tearing down runs after each test case.&lt;/p&gt;

&lt;p&gt;def teardown_method(self):&lt;br&gt;
       self.driver.quit()&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Test_login&lt;/strong&gt; — Implementation under this function is used for logging into the &lt;a href="http://accounts.lambdatest.com/login" rel="noopener noreferrer"&gt;LambdaTest dashboard&lt;/a&gt;. Here, I make use of &lt;a href="https://www.lambdatest.com/blog/how-to-use-selenium-sendkeys/" rel="noopener noreferrer"&gt;SendKeys in Selenium&lt;/a&gt; to fill out the login form so that I can login to the LambdaTest website. Here is the syntax of the SendKeys method in Selenium Python:&lt;/p&gt;

&lt;p&gt;element.send_keys("text to enter")&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For locating the respective WebElements, I have used the XPath locator in Selenium. However, you can use other popular Selenium locators like ID, Name, linktext, etc. for locating the WebElements.&lt;/p&gt;

&lt;p&gt;Shown below is the syntax of find_element_by_xpath() method in Selenium Python. Alternatively, you can also use the driver.find_element(By.XPATH) method for locating the element using XPath locator.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;element = driver.find_element_by_xpath("xpath_here")

driver.find_element(By.XPATH, "xpath")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here is how the entire login method (i.e. test_login) looks like:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def test_login(self):
       """
       this function logins you in lambdatest dashboard
       """
       LOGIN_URL = "[https://accounts.lambdatest.com/login](https://accounts.lambdatest.com/login)"
       DASHBOARD_URL = "[https://accounts.lambdatest.com/dashboard](https://accounts.lambdatest.com/dashboard)"
       self.driver.get(LOGIN_URL)
       login_email = self.driver.find_element_by_xpath(
           "//input[[@id](http://twitter.com/id)='email']"
       )
       login_password = self.driver.find_element_by_xpath(
           "//input[[@id](http://twitter.com/id)='password']"
       )
       login_button = self.driver.find_element_by_xpath(
           "//button[[@id](http://twitter.com/id)='login-button']"
       )

       login_email.send_keys(email)
       login_password.send_keys(password)
       login_button.click()

       # if we are on right page
       if self.driver.current_url == DASHBOARD_URL :
           assert True
           # time to get recent tests
           self.get_recent_tests()
       else:
           print(" something went wrong !!")
           assert False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;*&lt;em&gt;Get_recent_tests *&lt;/em&gt;— Once I have logged into the LambdaTest Dashboard, I fetch all recent tests from the lambdatest dashboard.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2732%2F1%2AMbGUnJA5WraF3eYsau-www.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2732%2F1%2AMbGUnJA5WraF3eYsau-www.png" width="800" height="449"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As seen above, .cut-text is a common class for all tags that we are interested to read. Next, I will perform web scraping using Selenium and Python for fetching the required information.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;titles = self.driver.find_elements_by_class_name("cut-text")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here, I clean and scrape text from the respective tags:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_recent_tests(self):
       titles = self.driver.find_elements_by_class_name("cut-text")
       titles_list = []
       for i in titles:
           titles_list.append(i.text)
       message = ' '.join(titles_list[0::2])
       print(message)
       send_email(message)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As seen in the implementation, we are using Selenium 3 Grid for testing. With the release of stable Selenium 4, many QA engineers are migrating Selenium automation tests to Selenium 4 grid. Before doing so, I recommend reading &lt;a href="https://www.lambdatest.com/blog/what-is-deprecated-in-selenium4/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep21_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Selenium 3 vs Selenium 4&lt;/a&gt; comparison so that tests can be migrated in a seamless manner.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sending emails using Selenium for Python
&lt;/h2&gt;

&lt;p&gt;Creating web bot using selenium with is not the only use. Python provides built-in smtplib library to send basic emails with secure connection using SMTP_SSL() and .starttls(). The smtplib library uses the RFC 821 protocol for Simple Mail Transfer Protocol (STMP).&lt;/p&gt;

&lt;p&gt;For sending an email using the smtplib module, I have created a function that accepts a message as a string and subsequently sends an email.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def send_email(message):
   context = ssl.create_default_context()
   try:
       server = smtplib.SMTP(smtp_server,port)
       server.ehlo() # Can be omitted
       server.starttls(context=context) # Secure the connection
       server.ehlo() # Can be omitted
       server.login(sender_email, sender_password)
       server.sendmail(sender_email, receiver_email, message)
       server.close()
   except:
       print(" failed to send email ")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Putting all together, this is how the overall implementation looks like in main.py.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver
import smtplib, ssl

port = 587
smtp_server = "smtp.gmail.com"
sender_password = "&amp;lt;YOUR_PASSWORD&amp;gt;"
sender_email = "&amp;lt;YOUR_EMAIL&amp;gt;"
receiver_email = "&amp;lt;EMAIL_WHERE_YOU_WANT_TO_SEND&amp;gt;"

def send_email(message):
   context = ssl.create_default_context()
   try:
       server = smtplib.SMTP(smtp_server,port)
       server.ehlo() # Can be omitted
       server.starttls(context=context) # Secure the connection
       server.ehlo() # Can be omitted
       server.login(sender_email, sender_password)
       server.sendmail(sender_email, receiver_email, message)
       server.close()
   except:
       print(" failed to send email ")

username = "&amp;lt;YOUR_LAMBDATEST_USERNAME&amp;gt;"
access_key = "&amp;lt;YOUR__LAMBDATEST_ACCESS_KEY&amp;gt;"

class TestClass():
   def setup_method(self):
       desired_caps = {
           "build": "your build name",
           "name": "your test name",
           "platform": "Windows 10",
           "browserName": "Chrome",
           "version": "92.0",
           "selenium_version": "3.13.0",
           "geoLocation": "IN",
           "chrome.driver": "91.0",
       }
       """
       Setup remote driver
               -------
               username and access_key can be found on lt platform

       """
       self.driver = webdriver.Remote(
           command_executor="https://{}:{}@hub.lambdatest.com/wd/hub".format(
               username, access_key
           ),
           desired_capabilities=desired_caps,
       )

   # tearDown runs after each test case
   def teardown_method(self):
       self.driver.quit()

   def test_login(self):
       """
       this function logins you in lambdatest dashboard
       """
       LOGIN_URL = "https://accounts.lambdatest.com/login"
       DASHBOARD_URL = "https://accounts.lambdatest.com/dashboard"
       self.driver.get(LOGIN_URL)
       login_email = self.driver.find_element_by_xpath(
           "//input[@id='email']"
       )
       login_password = self.driver.find_element_by_xpath(
           "//input[@id='password']"
       )
       login_button = self.driver.find_element_by_xpath(
           "//button[@id='login-button']"
       )

       login_email.send_keys(email)
       login_password.send_keys(password)
       login_button.click()

       # if we are on the right page
       if self.driver.current_url == DASHBOARD_URL :
           assert True
           # time to get recent tests
           self.get_recent_tests()
       else:
           print("something went wrong !!")
           assert False

   def get_recent_tests(self):

       titles = self.driver.find_elements_by_class_name("cut-text")
       titles_list = []
       for i in titles:
           titles_list.append(i.text)
       message = ' '.join(titles_list[0::2])
       send_email(message)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Scheduling Selenium with Python Test Script
&lt;/h2&gt;

&lt;p&gt;Making web bot using selenium python isn’t the main use. The scheduler allows to schedule test scripts to be run at a given point in time or under a given condition. For this task, I am using Windows Task Scheduler, which is a Windows GUI application. I am using the Win32com Library for programmatically scheduling the triggers.&lt;/p&gt;

&lt;p&gt;Win32com is the API library, a very thin Python wrapper that allows automating Windows Applications as an instance of the Windows Task Scheduler.&lt;/p&gt;

&lt;p&gt;Windows Task Scheduler uses COM (Component Object Model) objects. It allows controlling windows applications from another program or script. COM Objects are defined in the Windows registry. As COM objects are “objects”, they can be accessible to the test script and can be interacted with in a programmatic manner.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2Ac4jfeg1q_pqhSW5PYFGcXA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2Ac4jfeg1q_pqhSW5PYFGcXA.png" width="533" height="300"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is the run down of the Python code for running the developed test script in Windows task scheduler:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Defining win32com client from pywin32 library:&lt;/p&gt;

&lt;p&gt;scheduler = win32com.client.Dispatch('Schedule.Service')&lt;br&gt;
scheduler.Connect()&lt;br&gt;
root_folder = scheduler.GetFolder('\')&lt;br&gt;
task_def = scheduler.NewTask(0)&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Setting up few important Arguments&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;start time&lt;/strong&gt;: Set the start time for the script&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;start_time = datetime.datetime.now() + datetime.timedelta(minutes=1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Repetition.Duration&lt;/strong&gt;: Time duration (in days) for which the program execution needs to be repeated. In this particular case, I want to run this script for 10 days.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#Repeat for 10 days
num_of_days = 10
trigger.Repetition.Duration = "P"+str(num_of_days)+"D"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Repetition.Interval&lt;/strong&gt;: This variable tells after how much time the program needs to be executed. Here I have set to run the script after every 6 hours.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#For every 6 hour
trigger.Repetition.Interval = "PT6H"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;action.Path&lt;/strong&gt;: Path to the Python interpreter or pytest binary.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;action.Path = r'C:\Users\vinayak\selenium_test\env\Scripts\pytest.exe'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;action.Arguments&lt;/strong&gt;: Path of the script that has to be executed.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;action.Arguments = r'C:\Users\vinayak\selenium_test\main.py'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For writing our scheduler code, let’s create a scheduler.py file.&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import datetime&lt;br&gt;
import win32com.client

&lt;p&gt;scheduler = win32com.client.Dispatch('Schedule.Service')&lt;br&gt;
scheduler.Connect()&lt;br&gt;
root_folder = scheduler.GetFolder('\')&lt;br&gt;
task_def = scheduler.NewTask(0)&lt;/p&gt;
&lt;h1&gt;
  
  
  Start time of script
&lt;/h1&gt;

&lt;p&gt;start_time = datetime.datetime.now() + datetime.timedelta(minutes=1)&lt;/p&gt;
&lt;h1&gt;
  
  
  for running it one time
&lt;/h1&gt;

&lt;p&gt;TASK_TRIGGER_DAILY = 1&lt;br&gt;
trigger = task_def.Triggers.Create(TASK_TRIGGER_DAILY)&lt;/p&gt;
&lt;h1&gt;
  
  
  Repeat for 10 day
&lt;/h1&gt;

&lt;p&gt;num_of_days = 10&lt;br&gt;
trigger.Repetition.Duration = "P"+str(num_of_days)+"D"&lt;/p&gt;
&lt;h1&gt;
  
  
  For every 6 hour
&lt;/h1&gt;

&lt;p&gt;trigger.Repetition.Interval = "PT6H" &lt;br&gt;
trigger.StartBoundary = start_time.isoformat()&lt;/p&gt;
&lt;h1&gt;
  
  
  Create action
&lt;/h1&gt;

&lt;p&gt;TASK_ACTION_EXEC = 0&lt;br&gt;
action = task_def.Actions.Create(TASK_ACTION_EXEC)&lt;br&gt;
action.ID = 'TRIGGER BATCH'&lt;br&gt;
action.Path = r'C:\Users\vinayak\selenium_test\env\Scripts\pytest.exe'&lt;br&gt;
action.Arguments = r'C:\Users\vinayak\selenium_test\main.py'&lt;/p&gt;
&lt;h1&gt;
  
  
  Set parameters
&lt;/h1&gt;

&lt;p&gt;task_def.RegistrationInfo.Description = 'Test Task'&lt;br&gt;
task_def.Settings.Enabled = True&lt;br&gt;
task_def.Settings.StopIfGoingOnBatteries = False&lt;/p&gt;
&lt;h1&gt;
  
  
  Register task
&lt;/h1&gt;
&lt;h1&gt;
  
  
  If task already running, it will be updated
&lt;/h1&gt;

&lt;p&gt;TASK_CREATE_OR_UPDATE = 6&lt;br&gt;
TASK_LOGON_NONE = 0&lt;br&gt;
root_folder.RegisterTaskDefinition(&lt;br&gt;
   'Test Task',  # Task name&lt;br&gt;
   task_def,&lt;br&gt;
   TASK_CREATE_OR_UPDATE,&lt;br&gt;
   '',  # No user&lt;br&gt;
   '',  # No password&lt;br&gt;
   TASK_LOGON_NONE&lt;br&gt;
)&lt;br&gt;
&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  It’s A Wrap&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;Selenium webdriver with Python is used for applications like scraping websites or testing applications. But automation can also be used in many other ways as we have used it in our particular use-case. In this Selenium Python tutorial on web bot using selenium with python, we have seen how to create automated web bot using Selenium with Python.&lt;/p&gt;

&lt;p&gt;In the same way, Windows Task Scheduler can be used in many ways, not just to schedule tasks for Windows applications, it also allows you to run scripts in the background without having any need to remember them.&lt;/p&gt;

</description>
      <category>selenium</category>
      <category>python</category>
      <category>automation</category>
      <category>webdev</category>
    </item>
    <item>
      <title>The Ultimate Selenium Python Cheat Sheet for Test Automation</title>
      <dc:creator>Vinayak Sharma</dc:creator>
      <pubDate>Tue, 20 Sep 2022 14:29:46 +0000</pubDate>
      <link>https://forem.com/lambdatest/the-ultimate-selenium-python-cheat-sheet-for-test-automation-4gm0</link>
      <guid>https://forem.com/lambdatest/the-ultimate-selenium-python-cheat-sheet-for-test-automation-4gm0</guid>
      <description>&lt;p&gt;Python is one of the most popular programming languages for Selenium web automation since it provides a simplified syntax and lets you perform more with much less code! Thus, Python and Selenium form an ideal combination to perform web automation testing!&lt;/p&gt;

&lt;p&gt;For starters, Selenium is an open-source framework that is primarily used for automating interactions on the WebElements in the AUT (Application Under Test). Along with Python, Selenium also supports Java, C#, JavaScript, Ruby, and PHP. However, as per my experience, it would be fair to mention that Python will be my preferred language for &lt;a href="https://www.lambdatest.com/selenium-automation?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep20_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;Selenium web automation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Like me, more &amp;amp; more developers are picking up Python, which is rated as the third-most popular language as per the Stack Overflow Developer Survey 2021. Therefore, a Selenium Python cheat sheet could serve the purpose of providing insights into the useful Selenium Python APIs for realizing automation of websites (or web apps).&lt;/p&gt;

&lt;p&gt;If you’re new to Selenium and wondering what it is then we recommend checking out our guide — &lt;a href="https://www.lambdatest.com/selenium?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep20_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;What is Selenium?&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this blog, we explore the Python package that provides Python bindings for the Selenium WebDriver. For installing the Selenium WebDriver package, we use the Python Package Index (PyPI). Run the following command on the terminal to install Selenium for Python:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ pip install selenium
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This Python library wraps the Selenium WebDriver and provides methods for automating a range of tasks like filling up the form, logging into a website, clicking on buttons, and more. In addition, you can have a look at the &lt;a href="https://www.lambdatest.com/learning-hub/python-tutorial?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep20_rd&amp;amp;utm_term=rd&amp;amp;utm_content=learning_hub" rel="noopener noreferrer"&gt;Selenium Python tutorial&lt;/a&gt; that deep-dives into the integral aspects of Selenium Python from a web automation testing point of view.&lt;/p&gt;

&lt;p&gt;The commands mentioned in this Selenium Python cheat sheet can be used as a handy resource for anyone toying with Selenium and Python to automate web applications. If you need a quick recap of Python with Selenium, check out the tutorial that deep dives into the Selenium WebDriver architecture and highlights integral aspects related to &lt;a href="https://www.lambdatest.com/blog/selenium-webdriver-with-python/#Python?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep20_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Selenium WebDriver with Python&lt;/a&gt;. Let’s kick start our Selenium cheat sheet with Python!&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Import the Selenium library
&lt;/h2&gt;

&lt;p&gt;Before you can use any Selenium Python commands, you need to import the Selenium WebDriver package.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  2. Driver Initialization with Python
&lt;/h2&gt;

&lt;p&gt;After downloading the corresponding browser driver, you need to start the Selenium WebDriver and browser driver (e.g., ChromeDriver for Chrome, GeckoDriver for Firefox, etc.).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;For Chrome&lt;/strong&gt;&lt;/p&gt;
&lt;h1&gt;
  
  
  Initialize Chrome WebDriver
&lt;/h1&gt;

&lt;p&gt;driver = webdriver.Chrome()&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;For Firefox&lt;/strong&gt;&lt;/p&gt;
&lt;h1&gt;
  
  
  Initialize Firefox/Gecko WebDriver
&lt;/h1&gt;

&lt;p&gt;driver = webdriver.Firefox()&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;For Safari&lt;/strong&gt;&lt;/p&gt;
&lt;h1&gt;
  
  
  Initialize Safari WebDriver
&lt;/h1&gt;

&lt;p&gt;driver = webdriver.Safari()&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;For Internet Explorer&lt;/strong&gt;&lt;/p&gt;
&lt;h1&gt;
  
  
  Initialize IE WebDriver
&lt;/h1&gt;

&lt;p&gt;driver = webdriver.Ie()&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In case the location of the browser driver is not added to the PATH variable (or if it is not in the System Path), you need to add the following arguments:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;executable_path: Path to your Selenium WebDriver (binary file)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;options: Options regarding the web browsers execution&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;driver = webdriver.Chrome(executable_path="/usr/bin/chromedriver/", options=chrome_options )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  3. Setting Options in Selenium WebDriver
&lt;/h2&gt;

&lt;p&gt;The Options class in Selenium Python is commonly used in conjunction with Desired Capabilities to customize Selenium WebDriver.&lt;/p&gt;

&lt;p&gt;It helps to perform various operations like opening the browser(Chrome, Firefox, Safari, IE, Edge, etc.) in maximized mode, enabling and disabling browser extensions, disabling GPU mode, disabling pop-ups, and more. Therefore, it is important to be well-versed with this section of the Selenium Python cheat sheet since it will help solve &lt;a href="https://www.lambdatest.com/python-web-automation?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep20_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;Python web automation&lt;/a&gt;-specific problems that involve changing browser properties that we mentioned earlier.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;For Chrome&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;a. Importing Chrome options&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver
from selenium.webdriver.chrome.options import Options
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;b. Initialization of Chrome options&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chrome_options = Options()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;c. Adding Desired Capabilities&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chrome_options.add_argument("--disable-extensions")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;d. Adding Desired Capabilities to a session&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;driver = webdriver.Chrome(chrome_options=chrome_options)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;For Firefox&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;a. Importing Firefox options&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver
from selenium.webdriver.firefox.options import Options
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;b. Initialization of Firefox options&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;firefox_options = Options()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;c. Adding Desired Capabilities&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;firefox_options.set_headless()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;d. Adding Desired Capabilities to session&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;driver = webdriver.Firefox(options=firefox_options)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  4. Finding an element
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.lambdatest.com/learning-hub/selenium-locators" rel="noopener noreferrer"&gt;Locators in Selenium&lt;/a&gt; are majorly used for locating WebElements present in the DOM. Appropriate interactions (or actions) are further performed on the located WebElements. Some popular Selenium web locators are ID, Name, Link Text, Partial Link Text, CSS Selectors, XPath, TagName, etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Test on Latest Safari Desktop and Mobile Browsers for Cross Browser Compatibility. Test on real Mac machines running real &lt;a href="https://www.lambdatest.com/test-on-safari-browsers?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep20_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;Safari browser online&lt;/a&gt;&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Locate Elements by the ID attribute
&lt;/h2&gt;

&lt;p&gt;In this method, the element in the DOM is searched using the ID attribute. ID is unique for every element on the page. Thus, an ID can uniquely identify an element. For example, shown below is the use of the ID attribute for locating WebElements on the &lt;a href="https://accounts.lambdatest.com/login" rel="noopener noreferrer"&gt;LambdaTest login page&lt;/a&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2718%2F1%2A6rB9uerKifjU5mImBqraCA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2718%2F1%2A6rB9uerKifjU5mImBqraCA.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is how you can use the ID attribute in Selenium Python:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver

driver = webdriver.Chrome()
driver.get("[https://www.lambdatest.com](https://www.lambdatest.com)")
email_form = driver.find_element_by_id("testing_form")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Locate Elements by CSS Class
&lt;/h2&gt;

&lt;p&gt;Elements in HTML DOM can also be searched by Class Name, which is stored in the Class attribute of an HTML tag. A class can have many instances; it returns the first element with a matching class.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AJfgvvCsgJWB_dm8r6kvmtw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AJfgvvCsgJWB_dm8r6kvmtw.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is how Class Name is used for locating the Email Address element on the LambdaTest page:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver

driver = webdriver.Chrome()
driver.get(“https://www.lambdatest.com")
first_form_input = driver.find_element_by_class_name(“ form-control “)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Locate Elements by Name
&lt;/h2&gt;

&lt;p&gt;WebElements like input tag have a Name attribute associated with them. Selenium also provides a method to search for WebElements using the NAME attribute. If there are multiple elements of the same name, the first matched element is returned by the method.&lt;/p&gt;

&lt;p&gt;Here is the HTML code that contains an input element of Name — name!&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input name="name" type="text" value="user name" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Shown below is the usage of the Selenium Python method for locating the WebElement using the NAME property:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver

driver = webdriver.Chrome()
driver.get("[https://www.lambdatest.com](https://www.lambdatest.com)")
# for selection input with name attribute "name"
name_input = driver.find_element_by_name("name")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Locate Elements by XPath
&lt;/h2&gt;

&lt;p&gt;XPath uses path expressions to select nodes and locate the required WebElement. The find_element_by_xpath() method is used to locate an appropriate element in the document using XPath. You can read the &lt;a href="https://www.lambdatest.com/blog/complete-guide-for-using-xpath-in-selenium-with-examples/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep20_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Selenium XPath tutorial&lt;/a&gt; to gain deeper insights into using XPath for locating WebElements for Selenium web automation.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2718%2F1%2AftKLyjWkHd8QX-luduHE0g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2718%2F1%2AftKLyjWkHd8QX-luduHE0g.png"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Here is how the email element is located using the XPath attribute
&lt;/h2&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver

driver = webdriver.Chrome()
driver.get("[https://www.lambdatest.com](https://www.lambdatest.com)")
email_input = driver.find_element_by_xpath("//input[[@name](http://twitter.com/name)='email']")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Locate Element by tag name
&lt;/h2&gt;

&lt;p&gt;This method is used to locate and select WebElements using the HTML tag name. The find_element_by_tag_name() method is used to find tags such as H1, DIV, INPUT, etc. If there are multiple occurrences of the same tag, it returns the first matching tag.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2732%2F1%2AKGWx0B7GqJtR3xBEYGkK1Q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2732%2F1%2AKGWx0B7GqJtR3xBEYGkK1Q.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is how the email address element is located using the Tag Name:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver

driver = webdriver.Chrome()
driver.get("[https://www.lambdatest.com](https://www.lambdatest.com)")
email_input = driver.find_element_by_tag_name("input")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Browser &amp;amp; app testing cloud to perform both exploratory and automated &lt;a href="https://www.lambdatest.com/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep20_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;testing web&lt;/a&gt; browsers, real devices and operating systems.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Locate Element by Link text or Partial Link Text
&lt;/h2&gt;

&lt;p&gt;It selects elements based on the link text (either complete link text or partial link text). Partial link text does not look for an exact match of the string value since it looks for a string subset (in the link text).&lt;/p&gt;

&lt;p&gt;Link text locators in Selenium and partial link text locators work only on links of a given web application.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2718%2F1%2A_e3i_A5Euaduyd8OT6vRBA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2718%2F1%2A_e3i_A5Euaduyd8OT6vRBA.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is how you can use the link text locator to locate the desired WebElement on the LambdaTest login page:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver

driver = webdriver.Chrome()
driver.get("[https://www.lambdatest.com](https://www.lambdatest.com)")
email_input = driver.find_element_by_link_text('Start Free Testing')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here is how you can use the partial link text locator to locate the desired WebElement on the LambdaTest login page:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver

driver = webdriver.Chrome()
driver.get("[https://www.lambdatest.com](https://www.lambdatest.com)")
email_input = driver.find_element_by_partial_link_text('Start Free')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  5. Misc methods for finding elements
&lt;/h2&gt;

&lt;p&gt;Two private methods might be useful for locating page elements in conjunction with the “By” class for selecting attributes.&lt;/p&gt;

&lt;p&gt;It is to be noted that there is no difference between find_element_by_tag method and find_element(By.tag) method. By default, find_element_by_tag calls the find_element(By.tag) method.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;find_element&lt;/strong&gt; — It returns the first instance from multiple web elements with a particular attribute in the DOM. The method throws NoSuchElementException if no web elements are matching the required web locator. Check out our blog on common Selenium exceptions to gather a deeper understanding of when a particular Selenium exception is raised.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;find_elements&lt;/strong&gt; — It returns a list of all the instances of WebElements matching a particular attribute. The list is empty in case there are no matching elements in the DOM.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here are the attributes available for the By class:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;ID = “id”&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;XPATH = “xpath”&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;NAME = “name”&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;TAG_NAME = “tag name”&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;CLASS_NAME = “class name”&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;LINK_TEXT = “link text”&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;PARTIAL_LINK_TEXT = “partial link text”&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Shown below is an example of find_element method that uses the XPath locator to locate the desired WebElement:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium.webdriver.common.by import By
driver.find_element(By.XPATH, '//input[name()="password"]')
driver.find_elements(By.XPATH, '//input')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  6. Opening a URL (or document)
&lt;/h2&gt;

&lt;p&gt;Before performing any operation on the WebElements present on the page, opening the target URL (or test URL) is important. Here are some of the ways to open a URL in Selenium Python:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Test your web and mobile apps on &lt;a href="https://www.lambdatest.com/android-emulator-online?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep20_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;online Emulator Android&lt;/a&gt;. Ensure your apps are compatible across latest and legacy Android operating systems, devices, and browsers.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  driver.get(URL)
&lt;/h2&gt;

&lt;p&gt;The driver.get() method navigates to the page that is passed as a parameter to the method. Selenium WebDriver will wait until the page has fully loaded, post which it fires an “onload” event before returning control to the test script. You can check out our blog on Selenium Waits in Python to further understand handling waits in Selenium Python.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;driver.get("[https://www.lambdatest.com](https://www.lambdatest.com)")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  7. Refresh a page
&lt;/h2&gt;

&lt;p&gt;There are scenarios where you would want to refresh the contents on the page. The Refresh method of Selenium WebDriver is used for refreshing a web page.&lt;/p&gt;

&lt;p&gt;The driver.refresh() method refreshes the current web page. It does not take any arguments nor returns any value.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;driver.refresh()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  8. Writing text inside a WebElement
&lt;/h2&gt;

&lt;p&gt;The send_keys() method in Python is used for entering text inside a text element. The text to be entered is passed as an argument to the method. The same method can also be used for simulating key presses on any field (e.g. input fields of a form).&lt;/p&gt;

&lt;p&gt;Here is an example usage of the send_keys() method where the email address is passed to the text element on the LambdaTest signup page:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver

# create webdriver object
driver = webdriver.Chrome()

# get lambdatest
driver.get("[https://www.lambdatest.com/](https://www.lambdatest.com/)")

# get element 
element = driver.find_element_by_id("useremail")

# send keys 
element.send_keys("[emailid@lambdatest.com](mailto:emailid@lambdatest.com)")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  9. Clearing text of a WebElement
&lt;/h2&gt;

&lt;p&gt;The element.clear() method in Selenium Python is used to clear text from fields like input fields of a form, etc.&lt;/p&gt;

&lt;p&gt;Here is how the clear method is used for clearing contents in the email input box on the LambdaTest home page:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver

# create webdriver object
driver = webdriver.Chrome()

# get lambdatest
driver.get("[https://www.lambdatest.com/](https://www.lambdatest.com/)")

# get element 
element = driver.find_element_by_id("useremail")

# send keys 
element.clear()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  10. Clicking a WebElement
&lt;/h2&gt;

&lt;p&gt;The element.click() method in Selenium Python is used to click on an element like anchor tag, button tag, etc.&lt;/p&gt;

&lt;p&gt;Here is how a button present on the LambdaTest home page is clicked using the click() method:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver

# create webdriver object
driver = webdriver.Chrome()

# get lambdatest
driver.get("[https://www.lambdatest.com/](https://www.lambdatest.com/)")

# get element 
element = driver.find_element_by_id("useremail")

# send keys 
element.send_keys("[emailid@lambdatest.com](mailto:emailid@lambdatest.com)")

# get element 
button_element = driver.find_element_by_link_text("Start Free Testing")

# click the element
button_element.click()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  11. Dragging and Dropping a WebElement
&lt;/h2&gt;

&lt;p&gt;Dragging &amp;amp; dropping an object is one of the extensively used scenarios in popular apps (or softwares) like Canva, Google Drive, Trello, Asana, etc. The drag_and_drop(element, target) method in Selenium Python helps in automating the functionality of dragging WebElements from the source and dropping them on target area (or element).&lt;/p&gt;

&lt;p&gt;Actions class in Selenium has two methods through which you can perform drag &amp;amp; drop operation in browser compatibility testing. Do check out our detailed blog that deep dives into how to perform &lt;a href="https://www.lambdatest.com/blog/drag-and-drop-in-selenium-python/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep20_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;drag and drop in Selenium Python&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here is a simple example that shows the sample usage of drag_and_drop() method:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;element = driver.find_element_by_name("source")
target = driver.find_element_by_name("target")

from selenium.webdriver import ActionChains
action_chains = ActionChains(driver)
action_chains.drag_and_drop(element, target).perform()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  12. Selecting an option
&lt;/h2&gt;

&lt;p&gt;Select(element) provides useful methods for interacting with drop-downs, selecting elements, and more.&lt;/p&gt;

&lt;p&gt;Here is an example of how an element is selected using its index:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id('city'))
select.select_by_index(index)
select.select_by_visible_text("text")
select.select_by_value(value)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here are some of the various ways in which desired element is selected using the select_by_*() method:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2718%2F1%2A_e3i_A5Euaduyd8OT6vRBA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2718%2F1%2A_e3i_A5Euaduyd8OT6vRBA.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  13. Navigating between windows
&lt;/h2&gt;

&lt;p&gt;If there are multiple windows, you might need to switch to the right window before performing actions on the WebElements present in the DOM.&lt;/p&gt;

&lt;h2&gt;
  
  
  driver.switch_to_window(“window_name”)
&lt;/h2&gt;

&lt;p&gt;The switch_to_window() method of Selenium WebDriver lets you switch to the desired window. The window handle is passed as an argument to the switch_to_window() method.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;driver.switch_to_window("window_handle")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;All the subsequent calls of the WebDriver are now applicable to the window under focus (or the newly switched window).&lt;/p&gt;

&lt;h2&gt;
  
  
  driver.window_handles
&lt;/h2&gt;

&lt;p&gt;Window_handles property of the WebDriver returns handles of the windows. You can now use the switch_to_window() method to navigate to each window available in the list of window_handles.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for handle in driver.window_handles:
    driver.switch_to_window(handle)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  driver.current_window_handle
&lt;/h2&gt;

&lt;p&gt;The current_window_handle() method returns the handle of the current window (or window currently under focus)&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;handler = driver.current_window_handle
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  14. Switching to iFrames
&lt;/h2&gt;

&lt;p&gt;Selenium WebDriver can not access or locate the web elements inside an iFrame in the context of the main web page. Hence, you need to switch to an iFrame before accessing the WebElements inside the iframe.&lt;/p&gt;
&lt;h2&gt;
  
  
  driver.switch_to_frame(“frame_name”)
&lt;/h2&gt;

&lt;p&gt;The switch_to_frame() method in Selenium Python lets you switch the context of WebDriver from the context of the main page. We can also access subframes by separating the path and index with a dot.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;driver.switch_to_frame("frame_name.0.child")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  driver.switch_to_default_content()
&lt;/h2&gt;

&lt;p&gt;This method allows you to switch back to the context of the main page.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;driver.switch_to_default_content()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  15. Handling pop-ups and alerts
&lt;/h2&gt;

&lt;p&gt;There are three main types of popups &amp;amp; alerts that are commonly used in web applications:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Simple Alert&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Confirmation Alert&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Prompt Alert&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You have the option to switch to the alert, dismiss the alert, or accept the alert. You can check out our detailed tutorial on handling alerts and pop-ups in Selenium. Though the language used is C#, the fundamentals of alerts and pop-ups remain the same!&lt;/p&gt;
&lt;h2&gt;
  
  
  driver.switch_to.alert
&lt;/h2&gt;

&lt;p&gt;The switch_to.alert property of WebDriver returns the currently open alert object. You can use the object to accept, dismiss, read its contents, or type into the prompt.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;alert_obj = driver.switch_to.alert
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  alert_obj.accept()
&lt;/h2&gt;

&lt;p&gt;Once you have the handle of the alert window (e.g. alert_obj), the accept() method is used to accept the Alert popup.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;alert_obj = driver.switch_to.alert 
alert_obj.accept()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  alert_obj.dismiss()
&lt;/h2&gt;

&lt;p&gt;Once you have switched to the alert window (e.g. alert_obj), you can use the dismiss() method to cancel the Alert popup.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;alert_obj = driver.switch_to.alert 
alert_obj.accept()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  alert_obj.text()
&lt;/h2&gt;

&lt;p&gt;This method is used to retrieve the message included in the Alert popup.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;alert_obj = driver.switch_to.alert 
msg = alert_obj.text()
print(msg)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  16. Getting Page Source
&lt;/h2&gt;

&lt;p&gt;The page_source() method in Selenium WebDriver is used to get the target document’s page source (or test page).&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;page_source = driver.page_source
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  17. Navigating browser history
&lt;/h2&gt;

&lt;p&gt;Selenium WebDriver in Python provides some functionalities to move backward and forward in the web browser’s history&lt;/p&gt;
&lt;h2&gt;
  
  
  driver.forward()
&lt;/h2&gt;

&lt;p&gt;This method allows scripts to navigate one step forward in history.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;driver.forward()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  driver.back()
&lt;/h2&gt;

&lt;p&gt;This method allows scripts to navigate one step backward in history.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;driver.back()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  18. Handling Cookies in Selenium
&lt;/h2&gt;

&lt;p&gt;Handling cookies in Selenium WebDriver is one of the common scenarios that you might have to deal with in Selenium web automation. You can perform various operations like add, remove, get cookie name, and more.&lt;/p&gt;
&lt;h2&gt;
  
  
  driver.add_cookie()
&lt;/h2&gt;

&lt;p&gt;This method helps to set a cookie to a Selenium session. It accepts values in the key-value pair.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Go to the domain
driver.get("[https://www.lambdatest.com/](https://www.lambdatest.com/)")

# Now set the cookie. 
cookie = {'name' : 'user', 'value' : 'vinayak'}
driver.add_cookie(cookie)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  driver.get_cookies()
&lt;/h2&gt;

&lt;p&gt;This method outputs all the available cookies for the current Selenium session.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Go to the domain
driver.get("[https://www.lambdatest.com/](https://www.lambdatest.com/)")

driver.get_cookies()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  driver.delete_cookie()
&lt;/h2&gt;

&lt;p&gt;There is an option to delete a specific cookie or all the cookies associated with the current Selenium session.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# delete one cookie
driver.delete_cookie(cookie)
# delete all cookies
driver.delete_all_cookies()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Watch this video to understand how you can handle Cookies and perform different operations like deleting, getting the parameter values, and adding them to Selenium WebDriver using Java.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/WaNO9RTfEQw?start=2"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  19. Setting Window Size
&lt;/h2&gt;

&lt;p&gt;The set_window_size() method is used to set the browser window’s size to desired dimensions (in height and width).&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Setting the window size to 1200 * 800&lt;br&gt;
driver.set_window_size(1200, 800)&lt;br&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  

&lt;ol&gt;
&lt;li&gt;Configuring TimeOuts in Selenium WebDriver
&lt;/li&gt;
&lt;/ol&gt;
&lt;/h2&gt;


&lt;p&gt;When the browser loads a page, the WebElements inside the page may load at various time intervals. This might create complications when interacting with the dynamic elements present on the page.&lt;/p&gt;

&lt;p&gt;If an element is not present in the DOM of the web page, the locate method will raise an exception. &lt;a href="https://www.lambdatest.com/blog/types-of-waits-in-selenium/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep20_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Waits in Selenium&lt;/a&gt; lets you add delays (in ms or seconds) between the actions performed between loading the page and locating the required WebElement.&lt;/p&gt;

&lt;p&gt;Implicit wait and Explicit wait are the two major ways you can add delays in Selenium Python code for handling dynamic WebElements on the page.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implicit Wait in Selenium Python
&lt;/h2&gt;

&lt;p&gt;An implicit wait informs the Selenium WebDriver to examine the DOM for a particular amount of time when trying to find the WebElement that is not immediately available for access.&lt;/p&gt;

&lt;p&gt;By default, implicit wait is set as zero. However, once we define implicit wait, it is set for the lifetime of the WebDriver object. Check out our detailed tutorial that demonstrates the usage of Implicit wait in Selenium Python in greater detail.&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver

&lt;p&gt;driver = webdriver.Chrome()&lt;br&gt;
driver.implicitly_wait(10) # in seconds&lt;br&gt;
driver.get("&lt;a href="https://www.lambdatest.com/" rel="noopener noreferrer"&gt;https://www.lambdatest.com/&lt;/a&gt;")&lt;br&gt;
element = driver.find_element_by_id("testing_form")&lt;br&gt;
&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Explicit Wait in Selenium Python&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;Explicit wait in Selenium Python is used when we want to wait for a particular condition to happen before proceeding further in the code.&lt;/p&gt;

&lt;p&gt;There are some convenient methods provided by the Selenium WebDriver that let you wait until a particular condition is satisfied. For example, explicit waits can be achieved using the webdriverWait class combined with Expected Conditions in Selenium.&lt;/p&gt;

&lt;p&gt;Here are some of the Expected Conditions that can be used in conjunction with Explicit wait in Selenium Python:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;presence_of_all_elements_located&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;text_to_be_present_in_element&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;text_to_be_present_in_element_value&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;frame_to_be_available_and_switch_to_it&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;invisibility_of_element_located&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;title_is&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;title_contains&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;presence_of_element_located&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;visibility_of_element_located&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;visibility_of&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;element_located_selection_state_to_be&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;alert_is_present&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;element_to_be_clickable&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;staleness_of&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;element_to_be_selected&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;element_located_to_be_selected&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Element_selection_state_to_be&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Shown below is an example that demonstrates the usage of explicit wait where a non-blocking wait of 10 seconds is performed until the required WebElement is located (using its ID attribute):&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from selenium import webdriver&lt;br&gt;
from selenium.webdriver.common.by import By&lt;br&gt;
from selenium.webdriver.support.ui import WebDriverWait&lt;br&gt;
from selenium.webdriver.support import expected_conditions as EC

&lt;p&gt;driver = webdriver.Chrome()&lt;br&gt;
driver.get("&lt;a href="https://www.lambdatest.com/" rel="noopener noreferrer"&gt;https://www.lambdatest.com/&lt;/a&gt;")&lt;br&gt;
try:&lt;br&gt;
    element = WebDriverWait(driver, 10).until(&lt;br&gt;
        EC.presence_of_element_located((By.ID, "testing_form"))&lt;br&gt;
    )&lt;br&gt;
except:&lt;br&gt;
    print(“some error happen !!”)&lt;br&gt;
&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  

&lt;ol&gt;
&lt;li&gt;Capturing Screenshots
&lt;/li&gt;
&lt;/ol&gt;
&lt;/h2&gt;


&lt;p&gt;During the process of Selenium web automation, you might want to capture the screenshot of the entire page or screenshot of a particular WebElement.&lt;/p&gt;

&lt;p&gt;This is specifically used in scenarios where you want to check what went wrong in the test execution. Capture screenshots of WebElement using Selenium Python when you want to check which particular WebElement has created issues in the test execution process.&lt;/p&gt;

&lt;p&gt;The save_screenshot() method of Selenium WebDriver is used for capturing screenshots of a web page in Python.&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;capture_path = 'C:/capture/your_desired_filename.png'&lt;br&gt;
driver.save_screenshot(capture_path)&lt;br&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Conclusion&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;Get started with Selenium Python testing &amp;amp; that too free!!! Python is one of the most popular languages, and there is no denial that you can run complex Selenium operations with a few lines of code. In this Selenium Python cheat sheet, we covered some of the widely used Selenium Python commands primarily used for cross browser compatibility testing.&lt;/p&gt;

&lt;p&gt;This Selenium cheat sheet can be used as a guide (or reference) for quickly referring to the commands that might be of interest for your test code. I hope that you find this Selenium Python cheat sheet useful, do let me know if you come across any Selenium Python command that should be a part of the sheet.&lt;/p&gt;

&lt;p&gt;Happy Automation Testing With Python!&lt;/p&gt;

</description>
      <category>selenium</category>
      <category>python</category>
      <category>cheatsheet</category>
      <category>automation</category>
    </item>
    <item>
      <title>Most Exhaustive XPath Locators Cheat Sheet</title>
      <dc:creator>Vinayak Sharma</dc:creator>
      <pubDate>Mon, 19 Sep 2022 14:07:20 +0000</pubDate>
      <link>https://forem.com/testmuai/most-exhaustive-xpath-locators-cheat-sheet-b8</link>
      <guid>https://forem.com/testmuai/most-exhaustive-xpath-locators-cheat-sheet-b8</guid>
      <description>&lt;p&gt;The Selenium framework lets you interact with the WebElements in the DOM. For realizing the interaction(s), it is important to choose the appropriate locator from the available Selenium web locators. As per my opinion, Selenium web locators can be considered as the backbone of any web automation script.&lt;/p&gt;

&lt;p&gt;There are many options for web locators in Selenium — ID, Name, XPath, LinkText, Partial LinkText, Tag Name, and more. XPath is one of the widely preferred web locators, as it easily traverses through the DOM elements and attributes to identify an object.&lt;/p&gt;

&lt;p&gt;If you plan to use an XPath web locator to shape your &lt;a href="https://www.lambdatest.com/selenium-automation?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep19_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;test automation&lt;/a&gt; scripts, you might not have to look further than this comprehensive XPath cheat sheet. In addition, you can keep this XPath cheat sheet handy in scenarios where you want to have a quick look at the XPath syntax or other aspects related to this web locator.&lt;/p&gt;

&lt;p&gt;In this Selenium locators cheat sheet, we have demonstrated the XPath locator in the Java language. So, let’s get started with this exhaustive XPath cheat sheet that will come in super handy in Selenium automation testing.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is XPath Web Locator in Selenium
&lt;/h2&gt;

&lt;p&gt;XPath, which stands for XML Path Language, uses ‘path-like’ syntax to identify and navigate nodes in an XML or HTML document. It follows the XSLT(eXtensible Stylesheet Language Transformations) standard, which is predominantly used to navigate WebElements and attributes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AIfZbHYS8OwgzN4VMUPMmTA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AIfZbHYS8OwgzN4VMUPMmTA.png" width="533" height="300"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In order to navigate through the HTML document, the DOM (HTML tags, JavaScript, etc.) is used as a map where all the WebElements exist along with the WebElement that we intend to locate using the appropriate web locator.&lt;/p&gt;

&lt;p&gt;You can check out our blog on &lt;a href="https://www.lambdatest.com/blog/locators-in-selenium-webdriver-with-examples/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep19_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;locators in Selenium&lt;/a&gt; WebDriver to check other web locators that we have not covered in this XPath cheat sheet.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;This article explains the &lt;a href="https://www.lambdatest.com/blog/emulator-vs-simulator-vs-real-device/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep19_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;emulator vs simulator&lt;/a&gt; vs real device differences, the learning of which can help you select the right mobile testing solution for your business.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Different types of XPath in Selenium
&lt;/h2&gt;

&lt;p&gt;You can locate the desired WebElement in the DOM, either using the absolute path or using a relative path with respect to another element. In this part of the XPath cheat sheet, we look at the different ways in which you can use an XPath locator for locating a WebElement.&lt;/p&gt;

&lt;p&gt;Here are the two main types of XPath in Selenium:&lt;/p&gt;

&lt;h2&gt;
  
  
  Absolute XPath
&lt;/h2&gt;

&lt;p&gt;As the name indicates, an absolute XPath contains the complete path from the root element to the desired element. The downside of using absolute XPath is that any changes made in the path of the element, HTML path, etc., results in the failure of the XPath.&lt;/p&gt;

&lt;p&gt;Absolute Xpath begins with the single forward-slash(/), which means selecting the element from the document’s root node.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Syntax — Absolute Xpath&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/html/body/div[x]/div[y]/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Relative XPath
&lt;/h2&gt;

&lt;p&gt;In contrast to absolute XPath, a relative XPath starts by referencing the element we want to locate relative to a particular location. This means that the element is positioned relative to its normal position.&lt;/p&gt;

&lt;p&gt;Since the path of XPath is relative, it starts with a double forward-slash (//). As mentioned earlier in this Selenium locators cheat sheet, relative XPath is usually preferred for Selenium automation testing since it is not a complete path from the root element.&lt;/p&gt;

&lt;p&gt;Hence, any changes in the page design or the DOM hierarchy will have a minimal (to no) impact on the existing XPath selector.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Syntax — Relative Xpath&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//tagname[[@attribute](http://twitter.com/attribute)='value']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  The XPath syntax
&lt;/h2&gt;

&lt;p&gt;XPath uses path expressions to select nodes (or node-sets) in an HTML document. As shown below, the element or tag is selected by following a path or series of steps:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A6_U7HjjywOtgkminG8SknQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A6_U7HjjywOtgkminG8SknQ.png" width="533" height="300"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here are some of the useful path expressions that you can keep in handy as a part of the XPath cheat sheet:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2064%2F1%2Ad_gGvyCdvIa6FjcFltj0gA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2064%2F1%2Ad_gGvyCdvIa6FjcFltj0gA.png" width="800" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Perform cross browser compatibility testing across all &lt;a href="https://www.lambdatest.com/safari-browser-for-windows?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep19_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;Safari browsers for Windows&lt;/a&gt;, and many more real browsers and operating systems.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  XPath Expressions in Selenium
&lt;/h2&gt;

&lt;p&gt;XPath expression is a pattern that is used for selecting a set of nodes. These patterns are used by XSLT for performing transformations. XPointer also uses these patterns for addressing purposes.&lt;/p&gt;

&lt;p&gt;XPath uses a path expression to select the node or a list of nodes from an XML or HTML document.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Syntax — XPath Expression&lt;/strong&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//tagname[[@attribute](http://twitter.com/attribute)='value']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A6FHK8NyvrOUrIUt-I8BArg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A6FHK8NyvrOUrIUt-I8BArg.png" width="800" height="154"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Prefixes&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Prefixes in XPath are used at the beginning of the XPath expression.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AJyRStosCFD5sUg9Yawzbgg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AJyRStosCFD5sUg9Yawzbgg.png" width="800" height="335"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here are the examples of different kinds of Steps in XPath:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AVFl23YrsDU0dXpvXJpF9yA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AVFl23YrsDU0dXpvXJpF9yA.png" width="800" height="313"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Selecting Nodes&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this part of the XPath cheat sheet, we look at the different ways to select a node (or WebElement) in the document using XPath.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Predicates&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Predicates in XPath are used to find a specific node that contains a designated value. It uses syntax enclosed in square brackets.&lt;/p&gt;

&lt;p&gt;The table shown below in this Selenium locators cheat sheet shows some examples of predicates, along with different ways of selecting WebElements using those predicates.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2ANMLsAWeWYJUQP13Hj9jcQg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2ANMLsAWeWYJUQP13Hj9jcQg.png" width="800" height="594"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Chaining order&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Chaining order in XPath indicates the importance of order in an Xpath expression. The meaning of XPath changes with the change in order. For example a[1][&lt;a class="mentioned-user" href="https://dev.to/href"&gt;@href&lt;/a&gt;=’/’] and a[&lt;a class="mentioned-user" href="https://dev.to/href"&gt;@href&lt;/a&gt;=’/’][1] are different.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Indexing&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Indexing in XPath can be done using [ ] with a number that specifies the node we intend to select. It can also be done using functions like last() or position() that specify the index of the elements.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A2ujMI3UqBf8fHPvBRRWfZA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A2ujMI3UqBf8fHPvBRRWfZA.png" width="800" height="315"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Nesting predicates&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;XPath can also be nested to find the targeted node (or WebElement).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example — Nested Predicates&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//section[.//a[[@id](http://twitter.com/id)='btn']]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This example will return&lt;/p&gt;

&lt;p&gt;if it has an anchor tag descendant with an ID value of ‘btn.’&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Selecting Unknown Nodes&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Wildcards can also be used with an XPath locator to find unknown HTML document elements.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A5iRDKBINL2-EkoFcDqBlSw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A5iRDKBINL2-EkoFcDqBlSw.png" width="800" height="436"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Selecting Several Paths&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Using the ‘|’ operator in the XPath expression, you can select several paths.&lt;/p&gt;

&lt;p&gt;Below in this Selenium locators cheat sheet are examples that demonstrate the usage of the ‘|’ operator.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2ANae4VBsU41LtocEodeVbDQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2ANae4VBsU41LtocEodeVbDQ.png" width="800" height="137"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;&lt;a href="https://www.lambdatest.com/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep19_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;Browser test&lt;/a&gt; &amp;amp; app testing cloud to perform both exploratory and automated testing across 3000+ different browsers, real devices and operating systems.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  XPath Selectors in Selenium
&lt;/h2&gt;

&lt;p&gt;Selectors are used to ‘select’ certain parts of the HTML document specified by the element’s XPath. It’s the same as Axes in XPath.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Descendant selectors&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The descendant selectors indicate all the children of the current node, all children of children, etc. Attribute and namespace nodes are not included in descendant selectors. The parent of an attribute node is its element node, and on the other hand, attribute nodes are not the offspring of their parents.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AylGc35LtjGzEfvkeycHyag.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AylGc35LtjGzEfvkeycHyag.png" width="800" height="434"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Attribute Selectors&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The XPath attribute selector matches elements based on the presence or value of a given attribute.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2ASm3Fk-EVWSRd-rXmQyjI0g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2ASm3Fk-EVWSRd-rXmQyjI0g.png" width="800" height="368"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Siblings&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sibling in Selenium WebDriver is used for fetching a WebElement that is a sibling to a parent element. In this part of the XPath cheat sheet, we look at how to fetch elements using siblings in Selenium WebDriver.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2Amqm6qEHpoEK34P3fJVfxPA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2Amqm6qEHpoEK34P3fJVfxPA.png" width="800" height="250"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Using different Operators&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can use different operators like NOT, text matches (i.e., string, substring, etc.), union, and more to locate elements using operators and XPath in Selenium.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A9y_d0lxS4SglCU0Zy0k8lg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A9y_d0lxS4SglCU0Zy0k8lg.png" width="800" height="553"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Axes in XPath
&lt;/h2&gt;

&lt;p&gt;Axes in XPath represent a relationship from the current element to its relative element on the tree using either the absolute XPath or relative XPath. Its relationship to elements is identified as a parent, child, sibling, etc.&lt;/p&gt;

&lt;p&gt;They are named Axes because they refer to the axis on which elements lie relative to a particular WebElement. Shown below is the syntax of Axes in XPath:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;axisname::element[attribute]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This part of the Selenium locators cheat sheet shows the axis names and their relationship with the elements.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Element&lt;/th&gt;
&lt;th&gt;XPath&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;self&lt;/td&gt;
&lt;td&gt;For referring current elements&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;parent&lt;/td&gt;
&lt;td&gt;For referring parent of the current node&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;preceding&lt;/td&gt;
&lt;td&gt;Selects all elements that appear before the current element in the document&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;preceding-sibling&lt;/td&gt;
&lt;td&gt;Selects all siblings before the current elements&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;namespace&lt;/td&gt;
&lt;td&gt;Selects all namespace elements of the current element&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ancestor&lt;/td&gt;
&lt;td&gt;Selects all ancestors with a relationship like a parent, grandparent, etc. relative to the current element&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ancestor-or-self&lt;/td&gt;
&lt;td&gt;Selects the current element as well as all the ancestors of that element&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;attribute&lt;/td&gt;
&lt;td&gt;Selects all attributes of the current node&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;child&lt;/td&gt;
&lt;td&gt;Selects all children of the current element&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;descendant&lt;/td&gt;
&lt;td&gt;Selects all children, grandchildren, etc. of the current element&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;descendant-or-self&lt;/td&gt;
&lt;td&gt;Selects all descendants of the current elements and the current element itself&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;following&lt;/td&gt;
&lt;td&gt;Selecting everything in the document after the closing tag&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;following-sibling&lt;/td&gt;
&lt;td&gt;Selecting all siblings after the current element&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Here are some of the ways in which siblings in XPath can be used to find WebElements for Selenium automation testing.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2ABM8VJhsXt4IL4xvyUul54Q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2ABM8VJhsXt4IL4xvyUul54Q.png" width="800" height="459"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Operators in XPath
&lt;/h2&gt;

&lt;p&gt;An XPath expression can return either a node-set(div,a,li), a string, a Boolean (true or false), or a number. As a result, XPath provides many operators to manipulate their return values so that you get the desired value.&lt;/p&gt;

&lt;p&gt;In this part of XPath cheat sheet, we look at the list of operators that can be used with XPath expressions:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AkgDbx2NgvMGQKGudippT7w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AkgDbx2NgvMGQKGudippT7w.png" width="800" height="669"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Functions in XPath
&lt;/h2&gt;

&lt;p&gt;XPath provides a number of core libraries that bring in functionalities to deal with node sets, strings, booleans, and numbers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Syntax Demonstration&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;button[text()="Submit"]
    //button/text()
    //ol/li[position()=2]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Node functions
&lt;/h2&gt;

&lt;p&gt;There are seven kinds of nodes in XPath — element, attributes, namespaces, comments, document nodes, text, and processing instructions. First, let’s look at the permitted operations on nodes in further detail in this section of the XPath cheat sheet.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;name()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function provides the name of the element&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//[starts-with(name(), 'h')]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;text()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function Selects a text node.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//button[text()="Submit"]
    //button/text()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;position()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function provides the position of the element.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/div/a[position()&amp;lt;3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;last()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function selects the last node relative to the current element.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/div/a[last()]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;comment()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function selects the elements, which are comments.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/div/comment()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  String functions
&lt;/h2&gt;

&lt;p&gt;XPath string functions let you access elements using string type functions (e.g., contains, starts-with, etc.)&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;contains()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function is used to see if a certain element contains a particular string&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;font[contains([@class](http://twitter.com/class),"nav")]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;starts-with()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function is used to check if our element starts with a certain text.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;font[starts-with([@class](http://twitter.com/class),"nav")]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;ends-with()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Same as starts-with(), look (or check) at the end of the string.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;font[ends-with([@class](http://twitter.com/class),"nav")]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;substring-before()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function returns a string that is part of the input string before a given substring.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;substring-before("01/02", "/")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Output: 01&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;substring-after()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Same as substring-before(), returns a string that is part of the input string after a given substring.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;substring-after("01/02", "/")&lt;br&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Math functions&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;You can use mathematics-type functions like floor, ceil, sum, etc., to find elements using the XPath selector.&lt;/p&gt;

&lt;p&gt;Here are the math functions that we have covered in our XPath cheat sheet:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;ceiling(number)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function returns the smallest integer value greater than or equal to the decimal number.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;floor(number)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function returns the largest integer value less than or equal to the decimal number.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;round(decimal)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function returns a number that is the nearest integer to the given number.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;sum(elements)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function returns a number that is the sum of the numeric values of each element in a given element-set.&lt;/p&gt;

&lt;h2&gt;
  
  
  Boolean functions
&lt;/h2&gt;

&lt;p&gt;Boolean operators can also be used to find elements using the XPath selector.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;not()&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function is used to check whether certain conditions are met or not.&lt;/p&gt;

&lt;p&gt;Example:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;button[not(starts-with(text(),"Submit"))]&lt;br&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Browser console to locate XPath&lt;br&gt;
&lt;/h2&gt;

&lt;p&gt;Most modern web browsers (e.g., Chrome, Firefox, etc.) have a built-in debugging tool, which includes a feature that allows us to evaluate or validate XPath/CSS selectors. These tokens execute in the console panel, thereby providing you an option to validate the XPath selector.&lt;/p&gt;

&lt;p&gt;Here is a screenshot of the Debug Console in Chrome:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2732%2F1%2ARkDqWaFlOGm8hSKY3F2OZw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2732%2F1%2ARkDqWaFlOGm8hSKY3F2OZw.png" width="800" height="449"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this example, we have used $x(“//div”). With this, it selects all div elements from the DOM. An exception is thrown in case there is no matching node or elements in the DOM.&lt;/p&gt;

&lt;h2&gt;
  
  
  Obtain XPath using JQuery
&lt;/h2&gt;

&lt;p&gt;JQuery supports all basic kinds of XPath expressions; major ones are listed below in this part of the XPath cheat sheet:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy5f2tl1zyqo1tcwy5gfc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fy5f2tl1zyqo1tcwy5gfc.png" width="800" height="311"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Bonus Examples
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2Akax7Rat1rOusu2Q4CIUvqA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2Akax7Rat1rOusu2Q4CIUvqA.png" width="800" height="589"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;XPath is one of the widely used web locators in Selenium. However, coming up with an efficient XPath is an art that largely depends on the document’s structure and the current position of the WebElement.&lt;/p&gt;

&lt;p&gt;One of the most important things is finding the nearest unique WebElement relative to the target element and using the best technique to locate the WebElement. We covered the major aspects of the XPath locator in this exhaustive XPath cheat sheet.&lt;/p&gt;

&lt;p&gt;This Selenium locators cheat sheet can be used as a handy resource when you are performing Selenium automation testing.&lt;/p&gt;

&lt;p&gt;When it comes to Selenium automation testing, you can leverage the capabilities offered by cloud-based Selenium Grid like LambdaTest which lets you run tests on different browsers, platforms, and device combinations.&lt;/p&gt;

&lt;p&gt;Do share your views on how you would use this XPath cheat sheet for Selenium automation testing. Leave your feedback in the comments section…&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Happy Testing!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>xpath</category>
      <category>cheatsheet</category>
      <category>locators</category>
      <category>selenium</category>
    </item>
    <item>
      <title>Tutorial on Python Read Config File Using Selenium [With Example]</title>
      <dc:creator>Vinayak Sharma</dc:creator>
      <pubDate>Thu, 08 Sep 2022 14:32:34 +0000</pubDate>
      <link>https://forem.com/testmuai/tutorial-on-python-read-config-file-using-selenium-with-example-d4</link>
      <guid>https://forem.com/testmuai/tutorial-on-python-read-config-file-using-selenium-with-example-d4</guid>
      <description>&lt;p&gt;Before starting with this tutorial on Python read config file let’s understand Selenium. Selenium is one of the best automation tools used for running automated tests through which you can perform relevant actions with the WebElements on the page. The major advantage of Selenium is that it supports a number of popular programming languages (e.g., Python, Java, JavaScript, C#, PHP, and Ruby).&lt;/p&gt;

&lt;p&gt;When working with &lt;a href="https://www.lambdatest.com/blog/selenium-webdriver-tutorial-with-examples/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep08_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Selenium WebDriver&lt;/a&gt;, we need to follow the best practices to make the most out of the Selenium automation framework. One of them could be adding useful parameters like platform, browsers, browser versions, or device names in a manner that scaling up, organizing, and debugging the tests becomes easy. In addition, it should involve minimal changes in the test implementation! This is where configuration files come in handy, as configuration data can be added to those files with super ease. This, in turn, helps in improved maintenance of the test code.&lt;/p&gt;

&lt;p&gt;In this &lt;a href="https://www.lambdatest.com/blog/selenium-webdriver-with-python/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep08_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Selenium Python&lt;/a&gt; tutorial, we deep dive into the python read config file using Selenium.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Create Configuration Files With Constant Parameters Using Python
&lt;/h2&gt;

&lt;p&gt;Configuration files usually contain information that is organized in key:value pairs, where value is recognized by key. Configuration files usually have extensions like .ini, .cnf, .conf, .cfg, and .cf. There are several types of modules and techniques to create and parse configuration files in Python.&lt;/p&gt;

&lt;p&gt;Here are some of the commonly used configuration files in Python:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Python Configuration Files&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;JSON Configuration Files&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;YAML Configuration Files&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;INI Configuration Files&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;XML Configuration Files&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Run at scale automation tests on our online Appium grid or debug your web and mobile apps manually on the most powerful &lt;a href="https://www.lambdatest.com/android-emulator-online?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep08_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;Android Online Emulator&lt;/a&gt;&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Create python read config file
&lt;/h2&gt;

&lt;p&gt;Though Python files are not used to store configuration information, the best part is that storing configuration in Python files is a simple task. The major advantage of this approach is the ease in the management of configuration variables . For example, to store these configurations, we can create a config.py file.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;drivers_config = {
    "URL": "localhost.com",
    "FileName": "name.json",
}

# implementation comes here ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can use this config file in the actual implementation as shown below:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import config as cfg

driver = webdriver.Firefox()
driver.get(cfg.drivers_config["URL"])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As seen above, we simply imported the config file in the code before using the configuration parameters present in it. Now that we covered on python read config file, we now move to create JSON config files using the Python JSON module. &lt;/p&gt;

&lt;h2&gt;
  
  
  How to Create JSON configuration file
&lt;/h2&gt;

&lt;p&gt;JSON (JavaScript Object Notation) is a lightweight data-interchange format. It provides information in a human-readable format, making it easy for machines to parse the information stored in the JSON file. Shown below is an example that demonstrates how to use Python’s JSON module for creating a config.json file.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "drivers_config":{
        "URL":"localhost.com",
        "FileName" : "file.json",
      },
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can use this config file in the actual implementation as demonstrated below:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import json

# reading config file
file = open("config.json",)
data = json.load(file)

# using config file
print(data["drivers_config"]["URL"])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  How to create YAML configuration file
&lt;/h2&gt;

&lt;p&gt;YAML (YAML Ain’t Markup Language) is a human-readable data serialization language. In Python, we use the YAML module to parse the YAML file.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;drivers_config:
 URL: localhost.com
 FileName: file.json
other:
     Variable: “data “
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here is how you can read the YAML config file in Python:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import yaml

file = open("config.yml", "r") 
cfg = yaml.load(file)



print(cfg["drivers_config"]["URL"])
# this will print "localhost.com"

print(cfg["drivers_config"])
# this will print

# drivers_config
# {
#     “URL” : “localhost.com”   
#     “NameFile”: “file.json”
# }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Use &lt;a href="https://www.lambdatest.com/mobile-emulator-for-app-testing?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep08_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;android emulator for iOS&lt;/a&gt; to make sure your app works on mobile devices with different operating systems before releasing it.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How to create INI configuration file
&lt;/h2&gt;

&lt;p&gt;INI configuration file is a text-based structured syntax file that comprises key-value pairs.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[drivers_config]
URL=localhost.com
FileName=file.json

[other]
# other variables
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;To read this config file in Python, we will use the ConfigParser module. Run the below command on the terminal to install the ConfigParser module:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ pip install configparser
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here is how you can parse the INI configuration file in Python:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import configparser

file = open("config.ini","r")

config = configparser.RawConfigParser(allow_no_value=True)
config.read_file(file)

print( config.get("drivers_config","URL") )
# output will be localhost.com
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  How to create XML configuration file
&lt;/h2&gt;

&lt;p&gt;XML (Extensible Markup Language) lets you define rules for encoding documents that are easy to understand by humans and machines. The beautifulsoup module in Python is used for leveraging the advantages of XML configuration files.&lt;/p&gt;

&lt;p&gt;Run the below command on the terminal to install the beautifulsoup module:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ pip install bs4



&amp;lt;config&amp;gt;
    &amp;lt;drivers_config&amp;gt;
        &amp;lt;URL&amp;gt;localhost.com&amp;lt;/URL&amp;gt;
        &amp;lt;FileName&amp;gt;file.json&amp;lt;/FileName&amp;gt;
    &amp;lt;/drivers_config&amp;gt;
&amp;lt;/config&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;To parse this file, we will use the bs4 or beautifulsoup module in the implementation. Once parsed, the Python file will look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from bs4 import BeautifulSoup as bs

file = open('config.xml','r')
# parsing xml file
data = bs(file)

print(data.drivers_config.url.text)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Each parsing technique has its share of advantages &amp;amp; disadvantages. Hence, it is recommended to choose a technique that meets the project's needs and requirements.&lt;/p&gt;

&lt;p&gt;In the remaining part of the Python read config file tutorial, we would use the INI configuration file since INI is the widely preferred configuration file format by Python developers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Writing Selenium scripts for testing “add” functionality on a cloud Selenium Grid
&lt;/h2&gt;

&lt;p&gt;So far in this tutorial on Python read config file, we have covered the essentials of python read config file. So, how can you leverage the benefits offered by configuration files in Python to make Selenium tests more readable and maintainable? Well, first, you need to move to a scalable and reliable cloud-based Selenium Grid so that you can run Selenium tests across different browsers and platform combinations.&lt;/p&gt;

&lt;p&gt;LambdaTest is a cloud-based platform that enables you to perform live, interactive, and automated cross browser testing across 2000+ browsers and operating systems online. There are umpteen &lt;a href="https://www.lambdatest.com/blog/benefits-of-website-testing-on-cloud/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep08_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;benefits of cloud testing&lt;/a&gt;, something that cannot be achieved by running Selenium tests on a local test infrastructure. Porting existing Python code to the LambdaTest Selenium Grid involves minimal changes, making it easy for QA engineers to leverage the platform in the shortest possible time.&lt;/p&gt;

&lt;p&gt;For demonstrating Python config file usage with an example, we would use the LambdaTest ToDo App on which the relevant tests are performed. The desired browser capabilities are generated using the LambdaTest capabilities generator. &lt;/p&gt;

&lt;p&gt;Here is the set of operations performed on the LambdaTest Sample ToDo App:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Mark the first item and second items as complete. For this, we select the corresponding element using the Name locator (i.e., li1 and li2). You can check out our learning hub on &lt;a href="https://www.lambdatest.com/blog/locators-in-selenium-webdriver-with-examples/" rel="noopener noreferrer"&gt;Selenium Locators&lt;/a&gt; to ensure that you follow the best practices when using the appropriate web locators.&lt;/p&gt;

&lt;p&gt;check_box_one = driver.find_element_by_name("li1")&lt;br&gt;
check_box_one.click()&lt;/p&gt;

&lt;p&gt;check_box_two = driver.find_element_by_name("li2")&lt;br&gt;
 check_box_two.click()&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Find the text element using ID and enter the details of the new item using &lt;a href="https://www.lambdatest.com/blog/how-to-use-selenium-sendkeys/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep08_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;SendKeys in Selenium&lt;/a&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  Enter item in textfield
&lt;/h1&gt;

&lt;p&gt;textfield = driver.find_element_by_id("sampletodotext")&lt;br&gt;
textfield.send_keys("text we need to add")&lt;/p&gt;
&lt;h1&gt;
  
  
  Click on add button
&lt;/h1&gt;

&lt;p&gt;add_button = driver.find_element_by_id("addbutton")&lt;br&gt;
add_button.click()&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;After typing values in the text box, we will click the add button.&lt;/li&gt;
&lt;li&gt;For taking a screenshot, we will use the save_screenshot method provided by Selenium. You can read our in-depth blog that covers taking screenshots using Python and Selenium.&lt;/li&gt;
&lt;/ol&gt;
&lt;h1&gt;
  
  
  saving screenshot
&lt;/h1&gt;

&lt;p&gt;driver.save_screenshot(filename.png)&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Now comes the best part — creating an INI configuration file for storing the essential configuration parameters:) Create a configuration file named config.ini. This is the complete project structure: &lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AZaoVACelpNnYdv1zUV1tyg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AZaoVACelpNnYdv1zUV1tyg.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Now, create a config.ini file with the configurations that would be used in the test. The username and access key for using the LambdaTest Selenium Grid are available in the LambdaTest Profile Section.&lt;/p&gt;

&lt;p&gt;[USER_INFO]&lt;br&gt;
LT_USERNAME=YOUR_LT_USERNAME&lt;br&gt;
LT_ACCESS_KEY=YOUR_LT_ACCESS_KEY&lt;/p&gt;

&lt;p&gt;[SCREENSHOT_FILE_INFO]&lt;br&gt;
FILENAME=filename.png&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You could either pass this configuration file as a Command-Line argument or directly define it in the code.&lt;/p&gt;

&lt;p&gt;We will see both methods for parsing the configuration file:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Pre-defining configuration file details in the implementation&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Passing config file name as a command-line argument&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Though PyUnit is the default test automation framework in Python, QA engineers prefer PyTest for Selenium automation testing. To get started with PyTest, check out the below video from LambdaTest YouTube Channel.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/0ldd7v6j1Po"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  Predefined configuration file name in Python implementation
&lt;/h2&gt;

&lt;p&gt;In our case, we have named the Python configuration file as config.ini. This file will be parsed to read the relevant configuration information for usage in the code.&lt;/p&gt;

&lt;p&gt;Here is how we open and read contents from the config file:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;## getting config
with open("config.ini","r") as file:
    config = configparser.RawConfigParser(allow_no_value=True)
    config.read_file(file)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here is the entire implementation where we read the LT_USERNAME and LT_ACCESS_KEY from the configuration file. The read information is further used in the code for accessing the LambdaTest Grid. We have the PyUnit framework for the entire demonstration. Please refer to our &lt;a href="https://www.lambdatest.com/blog/using-pyunit-for-testing-a-selenium-python-test-suite/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep08_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;PyUnit Framework Tutorial&lt;/a&gt; to get more information on the said framework.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import configparser
import unittest
from selenium import webdriver

# getting config
with open("config.ini", "r") as file:
    config = configparser.RawConfigParser(allow_no_value=True)
    config.read_file(file)

username = config.get("USER_INFO", "LT_USERNAME")
access_key = config.get("USER_INFO", "LT_ACCESS_KEY")

class FirstSampleTest(unittest.TestCase):
    # Generate capabilities here [https://www.lambdatest.com/capabilities-generator/](https://www.lambdatest.com/capabilities-generator/)
    # setUp runs before each test case and
    def setUp(self):
        desired_caps = {
            "build": config.get("CAPABILITIES", "build"),
            "name": config.get("CAPABILITIES", "name"),
            "platform": config.get("CAPABILITIES", "platform"),
            "browserName": config.get("CAPABILITIES", "browserName"),
            "version": config.get("CAPABILITIES", "version"),
            "selenium_version": config.get("CAPABILITIES", "selenium_version"),
            "visual": config.get("CAPABILITIES", "visual"),
            "geoLocation": config.get("CAPABILITIES", "geoLocation"),
            "chrome.driver": config.get("CAPABILITIES", "chrome_driver"),
        }
      """
       Setup remote driver
            -------
            username and access_key can be found on lt platform

"""
        self.driver = webdriver.Remote(
            command_executor="[@hub](https://{}:{}&amp;lt;a href=).lambdatest.com/wd/hub"&amp;gt;https://{}:{}[@hub](http://twitter.com/hub).lambdatest.com/wd/hub".format(
                username, access_key
            ),
            desired_capabilities=desired_caps,
        )

# tearDown runs after each test case
    def tearDown(self):
        self.driver.quit()

# """ You can write the test cases here """
    def test_unit_user_should_able_to_add_item(self):
        # try:
        driver = self.driver

# Url
        driver.get("[https://lambdatest.github.io/sample-todo-app/](https://lambdatest.github.io/sample-todo-app/)")

# Click on checkbox
        check_box_one = driver.find_element_by_name("li1")
        check_box_one.click()

# Click on checkbox
        check_box_two = driver.find_element_by_name("li2")
        check_box_two.click()

# Enter item in textfield
        textfield = driver.find_element_by_id("sampletodotext")
        textfield.send_keys(config.get("ITEM_TO_ADD", "ITEM_VALUE"))

# Click on add button
        add_button = driver.find_element_by_id("addbutton")
        add_button.click()

# navigation to list to find the username to added item
        custom_xpath = (
            "//*[contains(text()," + config.get("ITEM_TO_ADD", "ITEM_VALUE") + ")]"
        )
        added_item = driver.find_element_by_xpath(custom_xpath).text

# saving screenshot
        driver.save_screenshot(config.get("SCREENSHOT_FILE_INFO", "FILENAME"))

if __name__ == "__main__":
    unittest.main()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Take a look at the aspects of simulation and explore various ways to use &lt;a href="https://www.lambdatest.com/blog/iphone-simulators-on-windows/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep08_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;iOS Simulator on PC&lt;/a&gt;&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Pass configuration file name as a Command-Line argument
&lt;/h2&gt;

&lt;p&gt;For accepting the command-line argument(s), we will use the sys module in Python to pass the configuration name.&lt;/p&gt;

&lt;p&gt;Here are some of the Python modules that can be used for passing command-line argument(s):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Using sys module&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Using argparse module&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Using optparse module and more&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For demonstration, we have used the sys module to read the command-line argument(s):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import configparser
import unittest
import sys
from selenium import webdriver

class sampleTest(unittest.TestCase):
    # default file name in case no arg passed
    config_file = "config.ini"

def setUp(self):
        self.config = configparser.RawConfigParser(allow_no_value=True)
        self.config.read(self.config_file)
        username = self.config.get("USER_INFO", "LT_USERNAME")
        access_key = self.config.get("USER_INFO", "LT_ACCESS_KEY")

## get CAPABILITIES from [https://www.lambdatest.com/capabilities-generator/](https://www.lambdatest.com/capabilities-generator/)

desired_caps = {
            "build": self.config.get("CAPABILITIES", "build"),
            "name": self.config.get("CAPABILITIES", "name"),
            "platform": self.config.get("CAPABILITIES", "platform"),
            "browserName": self.config.get("CAPABILITIES", "browserName"),
            "version": self.config.get("CAPABILITIES", "version"),
            "selenium_version": self.config.get("CAPABILITIES", "selenium_version"),
            "visual": self.config.get("CAPABILITIES", "visual"),
            "geoLocation": self.config.get("CAPABILITIES", "geoLocation"),
            "chrome.driver": self.config.get("CAPABILITIES", "chrome_driver"),
        }

"""
            Setup remote driver
            -------
            username and access_key can be found on lt platform

"""
        self.driver = webdriver.Remote(
            command_executor="[@hub](https://{}:{}&amp;lt;a href=).lambdatest.com/wd/hub"&amp;gt;https://{}:{}[@hub](http://twitter.com/hub).lambdatest.com/wd/hub".format(
                username, access_key
            ),
            desired_capabilities=desired_caps,
        )

# tearDown runs after each test case
    def tearDown(self):
        self.driver.quit()

# """ You can write the test cases here """
    def test_unit_user_should_able_to_add_item(self):
        # try:
        driver = self.driver

# Url
        driver.get("[https://lambdatest.github.io/sample-todo-app/](https://lambdatest.github.io/sample-todo-app/)")

# Click on checkbox
        check_box_one = driver.find_element_by_name("li1")
        check_box_one.click()

# Click on checkbox
        check_box_two = driver.find_element_by_name("li2")
        check_box_two.click()

# Enter item in textfield
        textfield = driver.find_element_by_id("sampletodotext")
        textfield.send_keys(self.config.get("ITEM_TO_ADD", "ITEM_VALUE"))

# Click on add button
        add_button = driver.find_element_by_id("addbutton")
        add_button.click()

# navigation to list to find added item
        custom_xpath = (
            "//*[contains(text()," + self.config.get("ITEM_TO_ADD", "ITEM_VALUE") + ")]"
        )
        added_item = driver.find_element_by_xpath(custom_xpath).text

# saving screenshot
        driver.save_screenshot(self.config.get("SCREENSHOT_FILE_INFO", "FILENAME"))

if __name__ == "__main__":
    if len(sys.argv) &amp;gt; 1:
        sampleTest.config_file = sys.argv.pop()
    unittest.main()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Trigger the following command on the terminal to read the command-line arguments:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ python -m single_test.py config.ini
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Visit the &lt;a href="https://automation.lambdatest.com/timeline/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sep08_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;Automation Dashboard&lt;/a&gt; on LambdaTest to get further information about the execution of tests on the cloud grid:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2718%2F1%2AI8isOviLX3G292qqzMfWow.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2718%2F1%2AI8isOviLX3G292qqzMfWow.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this Selenium Java tutorial, we have learnt about python read config file using the common configuration file formats like .cnf, .conf, .cfg, .cf, and .ini. We have also seen how multiple configuration files are read together, and their results can be merged into a single configuration using ConfigParser.&lt;/p&gt;

&lt;p&gt;We then performed Selenium automation testing to test the “add” functionality in the to-do list app and take a screenshot to verify our results using a cloud Selenium Grid.&lt;/p&gt;

</description>
      <category>python</category>
      <category>selenium</category>
      <category>config</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How To Perform Web Scraping with Python and Selenium</title>
      <dc:creator>Vinayak Sharma</dc:creator>
      <pubDate>Wed, 07 Sep 2022 18:09:20 +0000</pubDate>
      <link>https://forem.com/testmuai/how-to-perform-web-scraping-with-python-and-selenium-3igo</link>
      <guid>https://forem.com/testmuai/how-to-perform-web-scraping-with-python-and-selenium-3igo</guid>
      <description>&lt;p&gt;As per &lt;a href="https://insights.stackoverflow.com/survey/2020#technology-programming-scripting-and-markup-languages-all-respondents" rel="noopener noreferrer"&gt;Stack Overflow Survey 2020&lt;/a&gt;, Python holds the fourth position in the preferred programming languages category. Moreover, it is supported across a wide range of &lt;a href="https://www.lambdatest.com/blog/top-python-frameworks-for-automation/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sept07_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;test automation frameworks&lt;/a&gt;, including the Selenium framework. There web scraping with python and selenium is one of the most used combinations for smarter data collection and intelligent analysis.&lt;/p&gt;

&lt;p&gt;‘Data is the new oil,’ the ever-green quote by Humbly becomes much more relevant if the right methods are used for making the most out of the data. There is a plethora of information (read data) available on the internet, and acting on the right set of data can reap significant business benefits. Putting the right data collection methods in implementation can bring useful insights. On the other hand, incorrect data collection methods can result in obtuse data.&lt;/p&gt;

&lt;p&gt;Web scraping, surveys, questionnaires, focus groups, oral histories, etc., are some of the widely used mechanisms for gathering data that matters! Out of all the data collection methods, web scraping is considered the most reliable and efficient data collection method. For starters, web scraping (also termed web data extraction) is an automatic method for scraping (or obtaining) large amounts of data from websites. Selenium, the popular test automation framework, can be extensively used for scraping web pages. You can also learn more about &lt;a href="https://www.lambdatest.com/selenium?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sept07_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;what is Selenium&lt;/a&gt;? In this Selenium Python tutorial, we look at web scraping using Selenium and Python.&lt;/p&gt;

&lt;p&gt;We have chosen &lt;a href="https://www.lambdatest.com/learning-hub/python-tutorial?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sept07_rd&amp;amp;utm_term=rd&amp;amp;utm_content=learning_hub" rel="noopener noreferrer"&gt;Python&lt;/a&gt; — the popular backend programming language for demonstrating web page scraping. Along with scraping information from static web pages, we will also look into web scraping of dynamic pages using python and selenium. &lt;/p&gt;

&lt;h2&gt;
  
  
  What is Web Scraping
&lt;/h2&gt;

&lt;p&gt;Web Scraping, also known as “Crawling” or “Spidering,” is a technique for web harvesting, which means collecting or extracting data from websites. Here, we use bots to extract content from HTML pages and store it in a database (or CSV file or some other file format). Scraper bot can be used to replicate entire website content, owing to which many varieties of digital businesses have been built around data harvesting and collection.&lt;/p&gt;

&lt;p&gt;Web scraping with Python can help us extract an enormous volume of data about customers, products, people, stock markets, etc. The data has to be put to ‘optimal use’ for the betterment of the service. There is a debate whether web scraping is legal or not, the fact is that web scraping can be used for realizing legitimate use cases.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Test on Latest &lt;a href="https://www.lambdatest.com/test-on-safari-browsers?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sept07_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;Safari browser online&lt;/a&gt; and Mobile Browsers for Cross Browser Compatibility.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Use Cases for Web Scraping with Python
&lt;/h2&gt;

&lt;p&gt;Here are some of the valid (or authorized) use cases of web scraping in Python (and other Selenium-supported programming languages):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Search Engines&lt;/strong&gt;: Several Search bot engines crawl billions of websites and analyze their content for gathering meaningful search results. Search engine crawling is often called spidering. Spiders navigate through the web by downloading web pages and following links on these pages to find new pages available for their users. Then, they rank them according to different factors like keywords, content uniqueness, page freshness, and user engagement.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;E-commerce (Price Comparison)&lt;/strong&gt;: Price comparison websites use bots to fetch price rates from different e-commerce websites. Web scraping with Python is a reliable and efficient method of getting product data from target e-commerce sites according to your requirements. They acquire data by either building in-house web scraping methodologies or employing a DaaS (Data As A Service) provider that’ll provide the requisite data.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Sentiment Analysis&lt;/strong&gt;: Market research companies use web scraping with python for sentiment analysis. This kind of analysis helps companies gain customer insights, along with helping them understand how their customers behave to particular brands and products.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Job Postings&lt;/strong&gt;: Job listings for details about job openings and interviews are scraped from a collection of websites. The scraped information is then listed in one place so that it is seamlessly accessible to the users.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Legality of Web Scraping with Python?
&lt;/h2&gt;

&lt;p&gt;This is a debatable topic since it entirely depends on the intent of web scraping and the target website from which the data is being scraped. Some websites allow web scraping while several don’t. To see whether a website permits web scraping or not, we have to look at the website’s “robots.txt” file. We can find this file by adding “/robots.txt” at the end of the URL that you want to scrape.&lt;/p&gt;

&lt;p&gt;For example, if we want to scrape the LambdaTest website, we have to see the “robots.txt” file, which is at the URL &lt;a href="https://www.lambdatest.com/robots.txt" rel="noopener noreferrer"&gt;https://www.lambdatest.com/robots.txt&lt;/a&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;User-agent: *
Allow: /

Sitemap: [https://www.lambdatest.com/sitemap.xml](https://www.lambdatest.com/sitemap.xml)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Browser &amp;amp; app &lt;a href="https://www.lambdatest.com/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sept07_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;testing&lt;/a&gt; cloud to perform both exploratory and automated testing across 3000+ different browsers, real devices and operating systems.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Web Scraping with Python
&lt;/h2&gt;

&lt;p&gt;Getting started with web scraping in Python is easy since it provides tons of modules that ease the process of scraping websites. Here are some of the modules that you should be aware of to realize web scraping with Python:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Requests Library for Web Scraping&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;strong&gt;requests library&lt;/strong&gt; is used for making several types of HTTP requests like getting GET, POST, PUT, etc. Because of its simplicity and efficiency of use, it has a motto of “HTTP for Humans.”&lt;/p&gt;

&lt;p&gt;But, we can’t directly parse HTML using the requests library. It uses the lxml library to parse HTML.&lt;/p&gt;

&lt;p&gt;$ pip install requests&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Beautiful Soup Library for Web Scraping&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;BeautifulSoup Library is one of the widely-used Python libraries for web scraping. It works by creating a parse tree for parsing HTML and XML documents. Beautiful Soup automatically transforms incoming documents to Unicode and outgoing documents to UTF-8. It uses a custom parser to implement idiomatic navigation methods to search and transform the parse tree.&lt;/p&gt;

&lt;p&gt;$ pip install beautifulsoup4&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Scrapy Framework for Web Scraping&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Scrapy is a web scraping framework created by Pablo Hoffman and Shane Evans, co-founders of Scrapinghub. It is a full-fledged web scraping tool that does all the heavy lifting and provides spider bots to crawl various websites and extract the data. With Scrapy, we can create spider bots, host them on Scrapy Hub, or use their APIs. It allows us to develop fully functional spiders in a few minutes. We can also add pipelines to process and store data.&lt;/p&gt;

&lt;p&gt;Scrapy allows making the asynchronous request, which means it makes multiple HTTP requests simultaneously. This method saves a lot of time and increases our efficiency of scraping.&lt;/p&gt;

&lt;p&gt;$ pip install Scrapy&lt;/p&gt;

&lt;p&gt;Note: To further ease down the process of writing small tests, Python offers various tools and frameworks. Whether you are a Python beginner or an experienced programmer, pytest helps you write the tests you need and have them run in a reliable manner. For a quick overview on getting started with pytest, check out the video below from &lt;a href="https://www.youtube.com/channel/UCCymWVaTozpEng_ep0mdUyw" rel="noopener noreferrer"&gt;LambdaTest YouTube Channel&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/KeSWHW4Lx1E"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  Static and Dynamic Web Scraping with Python and Selenium
&lt;/h2&gt;

&lt;p&gt;There is a difference between static web pages and dynamic web pages. In a static web page, the content remains the same until someone changes them manually. On the other hand, the dynamic web page content of the page can differ for different visitors (e.g., content can change as per the &lt;a href="https://www.lambdatest.com/blog/geolocation-testing-with-selenium-using-examples/" rel="noopener noreferrer"&gt;geolocation&lt;/a&gt;, user profile, etc.). This increases its time complexity as dynamic web pages can render at the client-side, unlike static web pages, which render at the server-side.&lt;/p&gt;

&lt;p&gt;The static web page content or HTML documents are downloaded locally, and data can be scraped using relevant scripts. On the other hand, dynamic web page content (or data) is generated uniquely for every request after the initial page load request. For that case, we need to perform the following several actions using the manual approach:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.lambdatest.com/blog/selenium-click-button-with-examples/" rel="noopener noreferrer"&gt;Clicking on buttons&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.lambdatest.com/blog/complete-guide-to-access-forms-in-selenium-with-java/" rel="noopener noreferrer"&gt;Filling forms&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.lambdatest.com/blog/scroll-a-webpage-in-selenium-using-java/" rel="noopener noreferrer"&gt;Scrolling&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.lambdatest.com/blog/python-selenium-screenshots/" rel="noopener noreferrer"&gt;Taking a screenshot&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For this purpose, we need to automate websites, the same can be achieved using &lt;a href="https://www.lambdatest.com/blog/selenium-webdriver-tutorial-for-cross-browser-testing/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sept07_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Selenium WebDriver&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;In this article, look at how to debug websites using &lt;a href="https://www.lambdatest.com/blog/debug-websites-using-safari-developer-tools/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sept07_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;dev tools in Safari&lt;/a&gt;.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Scraping Dynamic Web Page using Python and Selenium
&lt;/h2&gt;

&lt;p&gt;Here are the prerequisites for realizing web scraping with Python and Selenium:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Beautifulsoup for scraping HTML content for websites:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;$ pip install beautifulsoup4&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Parsing HTML content of websites:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;$ pip install lxml&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Selenium for automation:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Installing Selenium using pip&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;$ pip install selenium&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Install Selenium using conda&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;$ conda install -c conda-forge selenium&lt;/p&gt;

&lt;h2&gt;
  
  
  Importing modules for web scraping with Python and Selenium
&lt;/h2&gt;

&lt;p&gt;For demonstration, we would be using the LambdaTest Grid. Cloud-based Selenium Grid on LambdaTest lets you run Selenium automation tests on 2,000+ browsers and operating systems online. You can perform parallel testing at scale using the cloud-based Grid. Once you create an account on LambdaTest, make a note of the user-name &amp;amp; access-key from the LambdaTest profile section.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup as bs
from lxml import html
from selenium import webdriver
from selenium.webdriver.common.by import By

// get your user key from LambdaTest platform and import using environment variables
// username = os.environ.get("LT_USERNAME")
// access_key = os.environ.get("LT_ACCESS_KEY")

// Username and Access Key assigned as String variables
username = "user_name"
access_key = "access_key"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now that we have imported all modules let’s get our hands dirty with web scraping with Python and Selenium.&lt;/p&gt;

&lt;h2&gt;
  
  
  Locating elements for web scraping with Python and selenium
&lt;/h2&gt;

&lt;p&gt;We would scrap the Blog Titles from the LambdaTest Blog Page. For this, we search for a particular topic and enter the required topic in the search bar.&lt;/p&gt;

&lt;p&gt;The following &lt;a href="https://www.lambdatest.com/blog/locators-in-selenium-webdriver-with-examples/?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sept07_rd&amp;amp;utm_term=rd&amp;amp;utm_content=blog" rel="noopener noreferrer"&gt;Selenium Locators&lt;/a&gt; can be used for locating WebElements on the web page under test:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Tag name&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Class name&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;IDs&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;XPath&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;CSS selectors&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here is an example of the usage of Selenium web locators to locate the search box on the page:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AYTwwGn-h4IE4C4GVmKsFDw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2AYTwwGn-h4IE4C4GVmKsFDw.png" width="768" height="359"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this case, we would use the XPath method driver.find_element(By.XPATH) to locate the search box on the page.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;driver.get("[https://www.lambdatest.com/blog/](https://www.lambdatest.com/blog/)")

searchBarXpath = "/html[1]/body[1]/section[1]/div[1]/form[1]/label[1]/input[1]"

# searching topic

textbox = driver.find_element(By.XPATH, searchBarXpath)
textbox.send_keys(topic)
 textbox.send_keys(Keys.ENTER)
 source = driver.page_source
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As we have got the content, we can parse it using lxml and beautifulsoup.&lt;/p&gt;

&lt;h2&gt;
  
  
  Scraping titles using beautifulsoup
&lt;/h2&gt;

&lt;p&gt;After parsing HTML source using lxml’s html.parser, we will find all h2 tags with class “blog-titel” and anchor tags inside them as these anchor tags contain the blog titles.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A1ampCaxACxqug1RHFauNOA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2A1ampCaxACxqug1RHFauNOA.png" width="768" height="379"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;title_list = [] 
soup = bs(source,"html.parser")
for h2 in soup.findAll("h2", class_="blog-titel"):
     for a in h2.findAll("a",href=True):
            title_list.append(a.text)

return title_list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Putting it all together
&lt;/h2&gt;

&lt;p&gt;Let’s combine the code to get the output.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup as bs
from lxml import html
from selenium import webdriver
from selenium.webdriver.common.by import By

// get your user key from LambdaTest platform and import using environment variables
// username = os.environ.get("LT_USERNAME")
// access_key = os.environ.get("LT_ACCESS_KEY")

// Username and Access Key assigned as String variables
username = "user_name"
access_key = "access_key"

class blogScraper:
    # Generate capabilities from here: [https://www.lambdatest.com/capabilities-generator/](https://www.lambdatest.com/capabilities-generator/)
    def setUp(self):
        capabilities = {
                "build" : "your build name",
                "name" : "your test name",
                "platform" : "Windows 10",
                "browserName" : "Chrome",
                "version" : "91.0",
                "selenium_version" : "3.11.0",
                "geoLocation" : "IN",
                "chrome.driver" : "91.0",
                "headless" : True
            }
        self.driver = webdriver.Remote(
           command_executor="[@hub](https://{}:{}&amp;lt;a href=).lambdatest.com/wd/hub"&amp;gt;https://{}:{}[@hub](http://twitter.com/hub).lambdatest.com/wd/hub".format(username, access_key),
           desired_capabilities= capabilities)

def tearDown(self):
        self.driver.quit()

def scrapTopic(self,topic):
        driver = self.driver

# Url
        driver.get("[https://www.lambdatest.com/blog/](https://www.lambdatest.com/blog/)")

searchBarXpath = "/html[1]/body[1]/section[1]/div[1]/form[1]/label[1]/input[1]"

        # searching topic
        textbox = driver.find_element_by_xpath(searchBarXpath)
        textbox.send_keys(topic)
        textbox.send_keys(Keys.ENTER)

        source = driver.page_source
        # scraping title
        title_list = [] 
        soup = bs(source,"html.parser")
        for h2 in soup.findAll("h2", class_="blog-titel"):
            for a in h2.findAll("a",href=True):
                title_list.append(a.text)

        return title_list

if __name__ == "__main__":
    obj = blogScraper()
    obj.setUp()
    print(obj.scrapTopic("scrap"))
    obj.tearDown()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here is the execution output:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['Scraping Dynamic Web Pages Using Selenium And C#', '9 Of The Best Java Testing Frameworks For 2021', 'The Best Alternatives to Jenkins for Developers', '10 Of The Best Chrome Extensions - How To Find XPath in Selenium', 'How To Take A Screenshot Using Python &amp;amp; Selenium?', 'Top 10 Java Unit Testing Frameworks for 2021', 'Agile Vs Waterfall Methodology', 'Why You Should Use Puppeteer For Testing']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Selenium is often essential to extract data from websites using lots of JavaScript as it’s an excellent tool to automate nearly anything on the web.&lt;/p&gt;

&lt;p&gt;Here is the execution snapshot of our &lt;a href="https://www.lambdatest.com/python-web-automation?utm_source=devto&amp;amp;utm_medium=organic&amp;amp;utm_campaign=sept07_rd&amp;amp;utm_term=rd&amp;amp;utm_content=webpage" rel="noopener noreferrer"&gt;Python web automation&lt;/a&gt; tests on the LambdaTest Automation Dashboard:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2APY8U9Vhg6IsmfO8-qKScpw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2APY8U9Vhg6IsmfO8-qKScpw.png" width="768" height="358"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this blog on web scraping with Python and Selenium, we deep-dived into web scraping as a technique that is extensively used by software developers for automating the extraction of data from websites. The purpose of web scraping is to allow companies and enterprises to manage information efficiently. There are a number of applications, such as VisualScrapper, HTMLAgilityPack, etc., that allow users to scrape data from static web pages. On the other hand, Selenium is the most preferred tool for dynamic web page scraping.&lt;/p&gt;

&lt;p&gt;Test automation supports a variety of browsers and operating systems. LambdaTest offers a cloud-based Selenium Grid that makes it easy to perform cross browser testing at scale across different browsers, platforms, and resolutions.&lt;/p&gt;

&lt;p&gt;Happy Scraping!&lt;/p&gt;

</description>
      <category>selenium</category>
      <category>python</category>
      <category>webdev</category>
      <category>testing</category>
    </item>
  </channel>
</rss>
