简体   繁体   中英

How to select an option from a listbox when it is not a select element? (Selenium, Python)

I'm trying to select the "Day" option from the second dropdown menu next to "Candlestick" onthis webpage

I'm unsure how to do this without select id. Please advise.

在此处输入图片说明

You can click on drop down icon and then click on the option you want to select. Can use below steps:

driver.get('https://www.dukascopy.com/swiss/english/marketwatch/historical/')
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[contains(@src, 'historical_data_feed')]")))
driver.execute_script("return arguments[0].scrollIntoView(true);", WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//li[text()='Indices (CFD)']"))))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//div[text()='Tick']"))).click()
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//div[text()='Day']"))).click()

Output在此处输入图片说明

Note : Key here issue here will be how to inspect items coming under dropdown. Foe that you need to inspect in Debug mode as below:

  1. Go to page open developer inspection mode
  2. Go to source Tab
  3. Click on drop down. it will show the options
  4. Now press F8, it will pause screen in debugger mode.
  5. Now inspect the option you want to select.

On the webpage, the dropdowns have a specific tag name ie select . To handle the drop down having select tag we use the Select class. In your case, it is not a dropdown so you have to handle it the way you handle rest of the elements. Like you have to click on the dropdown button and select the element you want to.

A small script is below for reference,

driver = webdriver.Chrome()
driver.get("https://www.dukascopy.com/swiss/english/marketwatch/historical/")
frame = driver.find_elements_by_tag_name("iframe")
print(len(frame))
driver.switch_to.frame(0)
driver.find_element_by_xpath("//div[text()='Tick']").click()
driver.find_element_by_xpath("//div[text()='Day']").click()

You may explicit wait as well for more less-error prone code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM