2016-06-10 42 views
1

我有一個包含三個webelement對象的硒webelement列表。我想要使用for循環獲取每個元素的索引。我怎麼能在Python中做到這一點?Python:如何迭代硒webelement列表並獲取索引?

目前正在做的是這樣的:

countries=Select(self.driver.find_element_by_xpath('//[@id="id_country"]')).options 
for index, value in countries: 
    print index 

,但它給我的錯誤

TypeError: 'WebElement' object is not iterable 
+0

,你可以分享你實際上已經試過嗎? – sumit

+0

我已添加更多解釋 –

回答

0

試試下面的例子

select_box = browser.find_element_by_xpath('//[@id="id_country"]') 
options = [x for x in select_box.find_elements_by_tag_name("option")] #this part is cool, because it searches the elements contained inside of select_box and then adds them to the list options if they have the tag name "options" 
for element in options: 
    print element.get_attribute("value") # or append to list or whatever you want here 
1

使用enumeratefor循環:

countries=Select(self.driver.find_element_by_xpath('//[@id="id_country"]')).options 
for index, value in enumerate(countries): 
    print index 

這將打印

0 
1 
2 

你也能指定起始索引,如果你不希望它是零索引:

countries=Select(self.driver.find_element_by_xpath('//[@id="id_country"]')).options 
for index, value in enumerate(countries, 10): 
    print index 


10 
11 
12