Python:如何迭代selenium webelement list并获取索引?

时间:2016-06-10 06:35:05

标签: python selenium

我有一个包含三个webelement对象的selenium webelement列表。我想使用for循环获取每个元素的索引。我怎么能在python中做到这一点?

目前正在这样做:

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

2 个答案:

答案 0 :(得分:1)

尝试以下示例

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 :(得分:0)

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