2016-11-09 74 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爲您更新選擇。

相關問題