如何在selenium python中找到子元素

时间:2017-09-14 05:48:25

标签: python selenium

我想找到"行项目"的子元素。并将它们存储在Ordered Dict表单中,然后将其传递给Excel。 下面给出的HTML和我的代码

<div class = "col-md-5 col-sm-5"
    <h3>....</h3>
    <div class = "row item">
       ::before
       <div class = "col-md-6 subtitle"> title</div>
       <div class = "col-md-6 ng-binding"> 1233344</div>
       ::after
     </div>
     <div class = "row item">
       ::before
       <div class = "col-md-6 subtitle"> name</div>
       <div class = "col-md-6 ng-binding"> abc</div>
       ::after
     </div>

同样,我有23个div&#39; row item&#39; class和我希望这些值以Ordered dict的形式出现,如

 Items_dict = {title:1233344, name:abc}

我的代码:

    for rowitem in  driver.find_elements_by_xpath('//div[@class="row item"]'):
                titles = rowitem.find_element_by_xpath('.//div[@class="row item"]/div[1]')
                values = rowitem.find_element_by_xpath('//div[@class="row item"]/div[2]')

                for title,value in zip(titles,values):
                    items_dict[title] = []
                    if(title.text and value.text):
                        items_dict[title.text].append(value.text)

1 个答案:

答案 0 :(得分:1)

首先删除for循环,尝试以下代码:

titles = driver.find_element_by_xpath('.//div[@class="row item"]/div[1]')
values = driver.find_element_by_xpath('//div[@class="row item"]/div[2]')
items_dict={};

for title,value in zip(titles,values):
       items_dict[title.get_attribute('text')] = value.get_attribute('text')