我有一个下拉元素,我想选择All选项,对应的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
元素没有使用browserInspect方法高亮显示,看起来这个下拉列表是由js触发的。我尝试使用这里描述的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方法,都不起作用。这让我很困扰,希望有人能帮上忙。
您不需要选择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()
试试这个:
driver.execute_script('document.getElementsByName("indicators_length")[0].value = 50;
如果它是在页面加载后创建和加载的,请确保添加一些睡眠以使其呈现;
我尝试使用Selenium Select类,它可以找到元素,但无法从元素中选择选项。不确定发生了什么,可能是元素上隐藏的类"jcf"。
话虽如此,我还是尝试了一下,下面是我的方法。试一下,它在我的系统上起作用,你必须处理"OK,I Agree"按钮的点击,我手动完成了。
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()