selenium,迭代列表,找到选择器

时间:2017-03-26 13:14:40

标签: python selenium css-selectors

我试图在selenium中找到webelement的属性,这给了我webelement的选择器。

我意识到以下属性可用于webelement:

tag_name
text
size
location
parent
id

我只是想知道是否有任何方法可以获取我正在迭代的特定元素的id或class_name。例如,我有以下硒(我使用硒碱,所以忽略"打开"功能)

    self.open('file:///myfile.htm')# Opens the url
    self.header = self.driver.find_element_by_class_name("my-class-name")
    name = self.driver.find_elements_by_css_selector('*')
    self.process_checks()
    for index in range(0,3):
        print name[index].id

我可以遍历元素中的元素" my-class-name"。但是,这些属性都没有给我实际的选择器名称。有没有办法确定,所以我可以做到以下几点:

如果名称[index] .selector =' my-div-inside-class-name':     doStuff()

get_attribute不是我需要的。这样做要容易得多:

    #Limit xpath to the surrounding div        
    self.header = self.driver.find_element_by_class_name("surrounding-div")
    #Get elements inside surrounding div, with "elements-i-need" in the class name
    self.name = self.header.find_elements_by_class_name('elements-i-need')
    for index in range(len(self.name)):
        #You can print each found element here.
        print(self.name[index].text)

1 个答案:

答案 0 :(得分:1)

正如答案中所提到的,我是这样做的:

#Limit xpath to the surrounding div        
self.header = self.driver.find_element_by_class_name("surrounding-div")
#Get elements inside surrounding div, with "elements-i-need" in the class name
self.name = self.header.find_elements_by_class_name('elements-i-need')
for index in range(len(self.name)):
    #You can print each found element here.
    print(self.name[index].text)