简体   繁体   中英

Get the sibling element of a WebElement without XPath [Python/Selenium]

If I'm locating an element using any of the find options, what is the best way to get the sibling element of the element I've located?

In my specific scenario, I'm using find_elements_by_xpath to get a specific list of elements. I'm then wanting to iterate through those elements, but I need to be able to access the sibling of each item found using the find_elements_by_xpath method.

I essentially am looking for this type of functionality:

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

If I'm overthinking this and there is a better approach, I'm all ears.

You can use the javascript to get the sibling element of any element that you have already found.

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

In your case, this should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM