How to interact with Selenium form web elements in Python

Overview

Selenium is an open-source web-based automation tool. We'll learn how to interact with the Selenium form web elementsTextBox, Submit Button, sendkeys(), click() in Python.

We can use the find_element() method to find text fields. We'll then use the send_keys() method to fill the text fields, and use the click() method to submit the form by clicking the submit button.

Example

from selenium import webdriver
import time
#specify where your chrome driver present in your pc
PATH=r"C:\Users\educative\Documents\chromedriver\chromedriver.exe"
#get instance of web driver
driver = webdriver.Chrome(PATH)
#provide website url here
driver.get("http://demo.guru99.com/test/newtours/")
#find input text fields
user_name = driver.find_element("name","userName")
password = driver.find_element("name","password")
#find submit button
submit = driver.find_element("name","submit")
#fill input text fields
user_name.send_keys("mercury")
password.send_keys("mercury")
#submit form
submit.click()

Explanation

  • Line 1: We import the webdriver from selenium package.
  • Line 2: We import the time.
  • Line 5: We provide the path where we placed the driver of the web browser. For chrome, it is chromedriver.exe in windows environment.
  • Line 8: We get the instance of the webdriver.
  • Line 11: We provide the URL to the driver.get() method to open it.
  • Lines 14–15: We use the find_element() method to get the input text fields—user_name and password.
  • Line 18: We use the find_element() method to get the submit button.
  • Lines 21–22: We use the send_keys() method to fill the input text fields—user_name and password. We pass text to place in that field as a parameter to the send_keys() method.
  • Line 25: We use the click() method to submit the form by clicking the submit button.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved