python - 如何在selenium python中查找子元素

标签 python selenium

我想找到“行项目”的子元素并将它们存储在有序字典形式中,然后将其传递到 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,我希望这些值采用有序字典的形式,例如

 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)

最佳答案

通过删除第一个 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')

关于python - 如何在selenium python中查找子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46211454/

相关文章:

python - 使用 Python 或 Bash 删除 PDF 的最后一页

python - 列表理解分配/比较在 256 之后失败

java - 在java和python中解析非常大的bz2 xml文件(逐个元素)

java - 元素MyElement在点(x,y)不可点击...其他元素将获得点击

python - 有没有办法在 python 中使用 selenium 获取 <div> 中的值?

python - for 每天同时循环 20 个数据帧

python - 在遍历字典时修改字典

docker - 如何在具有可见浏览器的 docker 容器中运行 Selenium 测试?

java - 有没有办法在 selenium webdriver 中获取 <embed> 标签资源

java - 如何使用java selenium点击jsp页面中vue js渲染的按钮