我有一个dropdown元素,我想选择全部选项,相应的HTML代码为:
<div class="dataTables_length" id="indicators_length">
<label>
<span class="result-mune">
<span>Results </span>per page:
</span>
<select name="indicators_length" aria-controls="indicators" class="jcf-hidden">
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="-1">All</option>
</select>
<span class="jcf-select jcf-unselectable">
<span class="jcf-select-text">
<span class="">25</span>
</span>
<span class="jcf-select-opener"></span>
</span>
</label>
</div>
select
元素未使用浏览器的 Inspect 方法突出显示,该下拉菜单似乎是由js触发的。
我尝试使用here中所述的Select类:
select = Select(self._wait.until(EC.presence_of_element_located_by((By.XPATH, "//div[@id = 'indicators_length']//select[@name = 'indicators_length']")))
select.select_by_value('-1')
不起作用。和ActionChain方法,甚至execute_script方法,都无法正常工作。这让我很困扰,希望有人能帮忙。
答案 0 :(得分:0)
尝试这个:
driver.execute_script('document.getElementsByName("indicators_length")[0].value = 50;
如果在页面加载后创建并加载了它,请确保添加一些睡眠以使其呈现;
答案 1 :(得分:0)
您真的不需要选择option
,只需单击span
,它将自动设置选项。
driver = webdriver.Chrome()
driver.get("......")
# click "OK, I Agree" cookies
driver.find_element_by_css_selector('.agree-button.eu-cookie-compliance-default-button').click()
# scroll down to make dropdown option visible
driver.find_element_by_css_selector('h4.pane-title').location_once_scrolled_into_view
select = driver.find_element_by_xpath('//span[@class="result-mune"]/following-sibling::span')
select.click()
# wait until javascript generate fake option element because it actually span
time.sleep(1)
select.find_element_by_css_selector('ul li span[data-index="4"]').click()
答案 2 :(得分:0)
我尝试使用Selenium Select类,它可以找到元素,但是不能从元素中选择一个选项。不确定发生了什么,可能是元素上的“ jcf-hidden”类。
话虽如此,我对此表示怀疑,这是我的做法。尝试一下,它在我的系统上有效,您必须处理“确定,我同意”按钮的单击,我是手动完成的。
import time
from selenium.webdriver import Chrome
driver = Chrome()
driver.get('https://www.topuniversities.com/university-rankings/world-university-rankings/2019')
# Remove this nasty time.sleep and implement webdriver wait
# Handle the OK, I Agree
time.sleep(5)
i_agree = driver.find_element_by_css_selector('button[class*="eu-cookie-compliance-default-button"]')
i_agree.click()
time.sleep(5)
# Open the Select
rankings_length = driver.find_element_by_id('qs-rankings_length')
select_opener = rankings_length.find_element_by_class_name('jcf-select-opener')
select_opener.click()
# loop through the list
select_content = rankings_length.find_element_by_class_name('jcf-list-content')
for content in select_content.find_elements_by_tag_name('li'):
if content.text == 'All':
content.click()