获取不带XPath的WebElement的同级元素[Python / Selenium]

问题描述 投票:2回答:1

如果我要使用find选项中的任何一个来定位元素,那么获取所定位元素的同级元素的最佳方法是什么?

在我的特定情况下,我正在使用find_elements_by_xpath获取元素的特定列表。然后,我想遍历这些元素,但是我需要能够访问使用find_elements_by_xpath方法找到的每个项目的同级对象。

我本质上是在寻找这种类型的功能:

elements = diver.find_elements_by_xpath("//path//to//elements")
for element in elements:
    sibling = element.find_element_by_css_selector(" + .sibling")

如果我考虑得太多了,并且有更好的方法,我会全力以赴。

python selenium xpath siblings
1个回答
2
投票

您可以使用javascript获取已经找到的任何元素的同级元素。

elements = diver.find_elements_by_xpath("//path//to//elements")
for element in elements:
    sibling = driver.execute_script("return arguments[0].nextElementSibling", element)

根据您的情况,应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.