Gabriel Gilabert
Gabriel Gilabert

Reputation: 37

selenium/python i cant select a item in dropdown

I am writing an automation for work and am stuck with a dropdown. The particular select box in question is as follows: enter image description here

If there is no select, how can I select one of the items?

Upvotes: 0

Views: 461

Answers (2)

rahul rai
rahul rai

Reputation: 2326

As is is not a select type item, you can first click on arrow in drop down to make available options visible. Then you can use Java script to select desired option from drop down. Reason we use javascript because it might be possible even after clicking on arrow few options may not be in screen freame.

driver = webdriver.Chrome('..\drivers\chromedriver')
driver.maximize_window()
driver.get("https://www.milanuncios.com/publicar-anuncios-gratis/formulario?c=393")

# Wait for upto 20 sec for page to load completely
WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//a[@class='ma-NavigationHeader-logoLink']")))

proviceDropDown = driver.find_element_by_xpath("//input[@id='province']//following-sibling::span")
#Scroll to dropdoen you want to select
driver.execute_script("arguments[0].scrollIntoView();", proviceDropDown)
proviceDropDown.click()


#Assume you are getting province name as parameter, I am doing a static assignment for demonstration 
proviceValue = "Granada"
optionToSelectXPath = "//ul[@class='sui-MoleculeDropdownList sui-MoleculeDropdownList--large']//span[text()='"+ proviceValue +"']")"
driver.execute_script("arguments[0].click();", driver.find_element_by_xpath(optionToSelectXPath ))

Upvotes: 0

Peter Quan
Peter Quan

Reputation: 808

A demo in Java language, just translate to Python by yourself (if you can't, let me know):

WebElement province = driver.findElement(By.xpath("//*[@id='province']"));

// scroll the page to the element `Provincia`
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView();", province);

// province.click(); doesn't work, I have not figured out why
new Actions(driver).moveToElement(province).click().perform();

// Notice this is the answer to your question
driver.findElement(By.xpath("//ul//li//span[contains(text(),'Granada')]")).click();

Upvotes: 1

Related Questions