31

I have this HTML:

<body>
    <p id='one'> 1A </p>
    <p id='two'> 2A </p>
    <p id='three'> 3A </p>
    <p id='four'> 4A </p>
    <p id='five'> 5A </p>
    <p id='six'> 6A </p>
    <p id='seven'> 7A </p>
</body>

I use the code below to get the first p tag element:

elem = driver.find_element_by_id('one')

Now, how to find the next sibling of elem?

2
  • You are missing a ' at the line <p id='three> 3A </p>. Commented May 27, 2014 at 10:59
  • possible duplicate of Xpath for choosing next sibling Commented May 27, 2014 at 12:08

3 Answers 3

38

I want to correct Mark Rowlands's answer,. The correct syntax will be

driver.find_element_by_xpath("//p[@id='one']/following-sibling::p")
Sign up to request clarification or add additional context in comments.

Comments

19

We need to pass elem to a JavaScript function and execute it. We cannot use it's name inside the JS function when we are passing elem to it, but we can use arguments. Here's an example of how you can get the next sibling of elem:

next_sibling = driver.execute_script("""
    return arguments[0].nextElementSibling
""", elem)

Take a look at this little example of how execute_script() function works:

sum = driver.execute_script("""
    console.log(arguments[0].innerHTML) // will print innerHTML of the element in console logs of the page
    return arguments[1] + arguments[2]
""", elem, 5, 6)

print(sum) # 11

1 Comment

@user3679414 This should be considered as the correct answer, because fully general, i.e. there is no need for a starting-point xpath. Just tested. +1
13

Using Xpath:

driver.find_element_by_xpath("//p[@id, 'one']/following-sibling::p")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.