问题
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