Retrieve Web Form Elements with WebDriver in Python

Q

How to Retrieve Web Page Form Elements with Selenium WebDriver in Python?

✍: FYIcenter.com

A

If a Web page is part of a Web application, it will most likely have an HTML form to allow users to enter and process data. This tutorial shows you how to Retrieve a Web page form and its elements with Selenium WebDriver.

Several methods from Selenium WebDriver classes will be used:

  • driver.get() - Loads a new Web page from the given URL in the current browser window. This is done using an HTTP GET operation, and the method will block until the load is complete.
  • driver.find_element_by_tag_name() - Searches and returns the first HTML element that matches the given tag name.
  • driver.find_elements_by_tag_name() - Searches and returns all HTML elements that matches the given tag name.
  • element.get_attribute() - Returns the value of the given attribute of this element.

1. Enter the following program, FormElement.py:

C:\fyicenter> type FormElement.py 

# FormElement.py
# Copyright (c) FYIcenter.com 
from selenium.webdriver import Chrome

driver = Chrome()
driver.get("http://sqa.fyicenter.com")

# get the first "form" element in the page
form = driver.find_element_by_tag_name("form")
action = form.get_attribute("action")
method = form.get_attribute("method")
print("Test Case - Review FORM elements:")
print("   <form action="+action+" method="+method+">")

# get all "input" elements in the "form"
list = form.find_elements_by_tag_name("input")
for input in list:
   type = input.get_attribute("type")
   name = input.get_attribute("name")
   value = input.get_attribute("value")
   size = input.get_attribute("size")
   src = input.get_attribute("src")
   alt = input.get_attribute("alt")
   print("      input type="+type+" name="+name+" value="+value
      +" size="+size+" src="/+src+" alt="+alt+">") 

print("   </form>")
driver.quit()

2. Run it.

C:\fyicenter>python FormElement.py

DevTools listening on ws://127.0.0.1:58904/devtools/browser/...
Test Case - Review FORM elements:
   <form action=http://sqa.fyicenter.com/index.php method=get>
      <input type=text name=Q value= size=28 src= alt=>
      <input type=image name= value= size=20 
       src=http://sqa.fyicenter.com/_search.png alt=Submit>
   </form>

As you can see, we are able to retrieve the FORM element and its INPUT sub-elements without any problem.

 

Submit Web Form with WebDriver in Python

Retrieve Web Page Title with WebDriver in Python

Using Selenium WebDriver Client Python API

⇑⇑ Selenium Tutorials

2019-10-27, 1160🔥, 0💬