How to handle dropdown with div tag in selenium python

How to Handle Dropdown with Div Tag in Selenium Python

Handling a dropdown with a div tag in Selenium using Python involves the following steps:

  1. Locate the div tag element that represents the dropdown on the web page.
  2. Click on the div tag element to open the dropdown options.
  3. Locate the specific option within the div tag dropdown and click on it.
  4. Verify that the option has been selected or perform any desired actions after selecting the option.

Here is an example of how to handle a dropdown with a div tag using Selenium in Python:

# Import necessary Selenium packages
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Set up driver (assuming ChromeDriver is installed)
driver = webdriver.Chrome()

# Navigate to the webpage containing the dropdown
driver.get("https://www.example.com")

# Locate the div tag representing the dropdown
dropdown_div = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "dropdown"))

# Click on the div tag to open the dropdown options
dropdown_div.click()

# Locate the specific option within the div tag dropdown
option = driver.find_element(By.XPATH, "//div[@id='dropdown']/div[contains(text(), 'Option 1')]")

# Click on the option to select it
option.click()

# Verify that the option is selected or perform additional actions

# Close the browser
driver.quit()

In the above example, we first import the necessary Selenium packages. We then set up the driver, navigate to the webpage, and locate the div tag representing the dropdown using its ID. We use the WebDriverWait to ensure that the div element is present before interacting with it. We then click on the div tag to open the dropdown options.

Next, we locate the specific option within the div tag dropdown using XPath and the contains() function to match the option text. We click on the option to select it.

Finally, you can add any additional actions or verifications you require after selecting the option. In this example, we simply close the browser after selecting the option.

Remember to substitute the appropriate elements and values for your specific case, such as the URL of the webpage and the ID or XPath of the dropdown div.

Leave a comment