Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find next sibling element in Selenium, Python?

Tags:

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?

like image 959
user3679414 Avatar asked May 27 '14 10:05

user3679414


People also ask

What is preceding sibling and following sibling?

The only difference in functionality is that of preceding. So, here, in contrast to Following-Sibling, you get all the nodes that are siblings or at the same level but are before your current node. The syntax for using Preceding-Sibling is: //tagname[@attribute='value']//preceding-sibling::tagname.

What is sibling in xpath?

Xpath Sibling is defined as a is a function for retrieving a web element that is a child of the parent element. The web element may be readily recognised or accessed using the sibling attribute of the Xpath expression if the parent element is known.


2 Answers

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

driver.find_element_by_xpath("//p[@id='one']/following-sibling::p") 
like image 173
jahr Avatar answered Sep 21 '22 17:09

jahr


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 
like image 33
ibodi Avatar answered Sep 23 '22 17:09

ibodi