Selenium迭代相同类别的多个元素并打印每个子内容(另一个相同类别)

huangapple go评论88阅读模式
英文:

Selenium iterate multiple elements with same class and print each sub content (another same class)

问题

使用Python,有人知道如何解决这一步骤吗?:

有一个包含多个class为"tag"的网页元素,每个元素内部都有一个class为"value"的元素。

我想要抓取这些内容,并将"value".text设置为每个"tag"变量。

有时候并不会有所有的标签,所以我也需要一个条件:

tags = driver.find_elements(By.CLASS_NAME, 'tag')

for tag in tags:
    if tag.text == 'Dog':
        dog = ...... .text
    .....

期望的输出:

dog= the dog name is Sam

cat= the cat name is Jam

英文:

with Python, do someone know how to solve this step?:

There is a webpage with multiple elements with class name "tag", and inside them, each one has one element called class= "value",

I want to order that scrap, and set "value".text in each "tag" variable

Sometimes there is not going to be all the tags, so I need a condition too:

    <div class="tag">
    "Dog"
    </div>
    <div class="value"> the dog name is Sam
  </div>
</div>
    <div class="tag">
    "Cat"
    </div>
    <div class="value"> the cat name is Jam
  </div>
</div>

expected output:

dog= the dog name is Sam

cat= the cat name is Jam

tags=driver.find_elements(By.CLASS_NAME,'tag')

for tag in tags:... 
      if tag.text == 'Dog': 
          dog= ...... .text

.....

答案1

得分: 0

tagValue = {}
for tag in tags:
if tag.text not in tagValue:
tagValue[tag.text] = value.text # 通过跟随同级 XPath 获取此元素

英文:
tagValue = {}
for tag in tags:
      if tag.text not in tagValue:
         tagValue[tag.text] = value.text #get this element by following sibling xpath

</details>



huangapple
  • 本文由 发表于 2023年3月21日 02:31:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75794047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定