2014-02-11 36 views
1

我的代碼使用硒從下拉菜單中選擇選項。我有一個代碼,看起來就像這樣:在Python中循環選項菜單硒

from selenium import webdriver 
browser = webdriver.Firefox() 
browser.get("http://www.website.com") 
browser.find_element_by_xpath("//select[@id='idname']/option[text()='option1']").click() 

這工作得很好。但是在下拉菜單中有許多選項,我希望循環下拉菜單中的所有項目。我準備了以下代碼來循環選項:

options = ["option1", "option2"] 
for opts in options: 
    browser.find_element_by_xpath("//select[@id='idname']/option[text()=opts]").click() 

這不起作用。任何有關如何獲得這樣一個循環的建議?我不明白Python中的循環?

謝謝。

回答

3

這應該適合你。該代碼將

  • 查找元素
  • 迭代通過列表
  • 獲得從下拉
  • 迭代所有的選項列表中的每個項目,選擇當前選項
  • 這是必要的重新選擇在每次通過下拉,因爲網頁已經改變

像這樣:

from selenium import webdriver 
from selenium.webdriver.support.ui import Select, WebDriverWait 
browser = webdriver.Firefox() 
browser.get("http://www.website.com") 

select = browser.find_element_by_xpath("//select[@id='idname']") #get the select element    
options = select.find_elements_by_tag_name("option") #get all the options into a list 

optionsList = [] 

for option in options: #iterate over the options, place attribute value in list 
    optionsList.append(option.get_attribute("value")) 

for optionValue in optionsList: 
    print "starting loop on option %s" % optionValue 

    select = Select(browser.find_element_by_xpath("//select[@id='idname']")) 
    select.select_by_value(optionValue) 
+0

謝謝,我今晚有時間嘗試這個。我將確保將此問題標記爲已回答。 –

+0

上面的答案適用於幾個較小的更正。 「/ option [text()='option1'」應該在它出現的兩個地方被刪除,「self.br.find_element_by_xpath」應該是「browser.find_element_by_xpath」。 –