How to retrieve values from drop down when select tag style attribute is set as display: none; in python selenium

半世苍凉 提交于 2019-12-12 16:35:49

问题


I am trying to scrap all combination of categories of drop down from one site. However text attribute of option is coming as blank only. Although while inspecting, I can see text is present for each option.

from selenium import webdriver
from selenium.webdriver.support.ui import Select

driver = webdriver.Chrome()
driver.get('https://www.fiyo.nl/')

driver.find_element_by_xpath('//*[@id="select_device_chosen"]/a').click()
select = Select(driver.find_element_by_xpath('//*[@id="select-device"]'))
print ([o.text for o in select.options]) 

Output:

['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

if I get text, I want to loop through all values to get different combination of other drop down.


回答1:


The <select> tag is having style attribute set as display: none; so you can use the following code block to print the options :

driver.find_element_by_xpath('//*[@id="select_device_chosen"]/a').click()
element = driver.find_element_by_xpath("//select[@id='select-device']")
driver.execute_script("arguments[0].removeAttribute('style')", element)
select = Select(driver.find_element_by_xpath("//*[@id='select-device']"))
print ([o.text for o in select.options])



回答2:


If you try like the following, the style tag is not a barrier to consider.

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.fiyo.nl/')

driver.find_element_by_xpath('//*[@id="select_device_chosen"]/a').click()
items = ' '.join([item.get_attribute("textContent") for item in driver.find_elements_by_xpath("//*[@class='chosen-results']//*[@class='active-result']")])
print(items.split())

driver.quit()


来源:https://stackoverflow.com/questions/49705523/how-to-retrieve-values-from-drop-down-when-select-tag-style-attribute-is-set-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!