Home > Net >  SELECT option from dropdown using Selenium Python
SELECT option from dropdown using Selenium Python

Time:11-15

been dealing with a countries dropdown using Selenium Python;

here is the Div tag of the drop-down menu:

<div cdk-overlay-origin="" ><div id="mat-select-value-1"><span ></span><!----><!----></div><div ><div ></div></div></div><!---->

and here is the Div tag for the targeted option:

<div id="mat-select-value-1"><!----><span style=""><span >MAROKO</span><!----><!----></span><!----></div><div ><div ></div></div>

and here's the specific Span Tag for the targeted option

<span >MAROKO</span><!----><!---->

the code used to select an option from that dropdown is :

Country=browser.find_element(By.ID, 'mat-select-value-1')
time.sleep(5) 
drop=Select(Country) 
time.sleep(5) 
drop.select_by_visible_text("MAROKO")

output

Exception has occurred: UnexpectedTagNameException
Message: Select only works on <select> elements, not on <div>
  File "C:\Users\test\form.py", line 31, in <module>
    drop=Select(Country)

I went with drop.select_by_visible_text since I believe it's the only available option!

Imports used

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
import time

I would appreciate any helpful comment.

Cheers

Tried this specifcly this;

WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id="mat-radio-2"]/label/span[1]/span[1][text()='MAROKO']"))).click()

but it seems that there's a syntax error

CodePudding user response:

You can use the selenium's Select() class only for html <select> tags. But this dropdown is implemented with <div>, so you can handle it just like html elements.
First you need to click the dropdown to expand the options and then click the option you need:

WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@]'))).click()
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'mat-select-value-1'))).click()

I've created the locators using the html parts you provided. Perharps you will need to update them.

  • Related