2016-11-09 101 views
1

到Python的选择我是比较新的(当然,超过比较)。我需要从下拉菜单中选择一个选项。我尝试了几乎所有可用的解决方案。但似乎没有任何工作。 这是我与交互的页面:http://www.europarl.europa.eu/plenary/en/debates-video.html?action=1&tabActif=tabResult#sidesForm 这是给我的问题网页的源文件的一部分:无法选择从下拉菜单中的Python硒

<select id="criteriaSidesLeg" name="leg" style="display:none;" aria-disabled="false"> 

        <option title="2014 - 2019" value="8">2014 - 2019</option> 

        <option title="2009 - 2014" value="7" selected="selected">2009 - 2014</option> 

        <option title="2004 - 2009" value="6">2004 - 2009</option> 

        <option title="1999 - 2004" value="5">1999 - 2004</option> 

</select> 

我曾尝试到现在是:

import time 
from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
from selenium.webdriver.support.ui import Select 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.common.by import By 
# pressing the botton year menu making the element visible 
elem_year_arrow=driver.find_element_by_id("criteriaSidesLeg-button") 
elem_year_arrow.click() 
year= driver.find_element_by_id('criteriaSidesLeg') 
for option in year.find_elements_by_tag_name('option'): 
    if option.text=='2009 - 2014': 
     option.click() 
     break 

这给了我这个错误:

selenium.common.exceptions.ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated 
    (Session info: chrome=54.0.2840.87) 
    (Driver info: chromedriver=2.25.426935 (820a95b0b81d33e42712f9198c215f703412e1a1),platform=Mac OS X 10.10.5 x86_64) 

我也试过这个其他的解决办法

wait = WebDriverWait(driver, 10) 
element = wait.until(EC.visibility_of_element_located((By.ID,"criteriaSidesLeg"))) 
select = Select(element) 
select.select_by_value('7') 

这不是给我的错误,但这个TimeoutException异常

raise TimeoutException(message, screen, stacktrace) 
selenium.common.exceptions.TimeoutException: Message: 

所以我也试图执行此命令行:

driver.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].value == arguments[1]){ select.options[i].selected = true; } }", element, "01") 

但同样得到上述超时异常 如何进行? 我希望问题很清楚,并且提前谢谢大家!

回答

1

你试图处理错误的元素。试试这个代码,让我知道在任何问题时:

driver.find_element_by_xpath('//a[@id="criteriaSidesLeg-button"]').click() 
driver.find_element_by_xpath('//a[text()="2009 - 2014"]').click() 

同样不使用XPath

driver.find_element_by_id('criteriaSidesLeg-button').click() 
driver.find_element_by_link_text('2009 - 2014').click() 
+0

这个完美工作和解决我的问题!你人真好! – Bene

0

与你链接到的是,选择框从管理该网站的问题只有JS,并已被非选择下拉菜单取代。如果您想要应用自定义用户体验(UX不一定适用于操作系统定义的选择行为),这很常见。

你可以有硒执行一些JavaScript这将删除选择display:none样式,然后做你的选项选择。

driver.execute_script("document.getElementById('criteriaSidesLeg').setAttribute('style','')"); 

或者也可以模拟psuedo选择元素上的必要点击并让站点JS为您更新选择。