What are the ways of submitting a form in Selenium with python?


There are multiple ways of submitting a form in Selenium. One of the methods is to directly use the click() method on the form submitting button. The next approach is to use the submit() method on the form page.

  • Using the submit() method.

    This method shall simply submit the form after the required data is entered on the form page.

Syntax

driver.find_element_by_xpath("//input[class ='gsc-search']").submit()
  • Using the click() method.

    This method shall click on the submit button of the form after the required data is entered on the form page.

Syntax

driver.find_element_by_xpath("//button[id ='value']").click()

Example

Code Implementation with submit() method.

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of id and enter text
driver.find_element_by_id("gsc-i-id1").send_keys("Selenium")
# submit the text contents
driver.find_element_by_id("gsc-i-id1").submit()
#to close the browser
driver.close()

Code Implementation with click() method for form submission.

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of id and enter text
driver.find_element_by_id("gsc-i-id1").send_keys("Selenium")
# identifying the button then using click() method
driver.find_element_by_xpath("//button[contains(@class,'gsc-search')]") .click()
#to close the browser
driver.close()

Updated on: 29-Jul-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements