Sunday, October 9, 2022

Handling static and dynamic drop down

 Static dropdown values already set in html file.

import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

## https://github.com/mozilla/geckodriver/releases
service_obj = Service("/Users/UReddy/documents/geckodriver.exe")
driver = webdriver.Firefox(service=service_obj)
driver.maximize_window()
driver.get("https://rahulshettyacademy.com/angularpractice")
#time.sleep(5)
#Static Dropdown -- select tags in html, so use Select class in python
dropdown= Select(driver.find_element(By.ID,"exampleFormControlSelect1"))
#time.sleep(5)
dropdown.select_by_index(1)
#time.sleep(5)
dropdown.select_by_visible_text("Female")
#time.sleep(5)
##driver.close()

## dropdown.select_by_value ## with value attribute defined in options.
driver.get("https://rahulshettyacademy.com/loginpagePractise")
#time.sleep(5)
dropdown= Select(driver.find_element(By.CSS_SELECTOR,"select[class='form-control']"))
dropdown.select_by_value("consult")
time.sleep(5)
driver.close()


for static dropdown select html tag is there so we use Select class.

But for dynamic dropdown, it uses input tag only.

So, we can get all the list items once you type something in search and then loop through one by one for searching the element required.

import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

service_obj = Service("/Users/UReddy/documents/geckodriver.exe")
driver = webdriver.Firefox(service=service_obj)
driver.get("https://rahulshettyacademy.com/dropdownsPractise")
driver.find_element(By.ID,"autosuggest").send_keys("ind")
time.sleep(2)
countries = driver.find_elements(By.CSS_SELECTOR, "li[class='ui-menu-item'] a")
print(len(countries))

for country in countries:
if country.text == "India":
country.click()
break

## .text() will display text of elements only if it is loaded during site first load.
## dynamic values added later don't show here, so below will be empty.
print(driver.find_element(By.ID,"autosuggest").text)

## so use the get_attribute.
print(driver.find_element(By.ID,"autosuggest").get_attribute("value"))

assert driver.find_element(By.ID,"autosuggest").get_attribute("value")=="India"


No comments:

Post a Comment