首页 > 解决方案 > What is the difeerence between parent function and child function in xpath of selenium

问题描述

URL==> http://demo.guru99.com/test/login.html I use the above url for testing purpose

i try to find the web element using parent and child function in xpath,but child and parent function give me an same result,i use the below command

parent function==> $x("//div[@class='container-fluid']//parent::div")
child function==> $x("//div[@class='container-fluid']//child::div")

Observe that i use the same web element and try to fing it's parent and child element but after running the above cmd i get the similar result Execute the cmd in cosole tab How can have same element as a parent as well as child for particular web element Please help in above and if not clear the question let me know i try to more describe the question Thank you in advance

标签: functionseleniumxpath

解决方案


Breaking it down:

//div[@class='container-fluid']//parent::div
  1. // select the root and all of its descendants
  2. div[@class='container-fluid'] from all of the nodes selected in step 1., select all child div elements with an attribute class equal to 'container-fluid'
  3. // select all nodes selected in step 2 and all of their descendants
  4. parent::div starting from the nodes selected in step 3, select all parents of those nodes that are div elements
//div[@class='container-fluid']//child::div
  1. // select the root and all of its descendants
  2. div[@class='container-fluid'] from all of the nodes selected in step 1., select all child div elements with an attribute class equal to 'container-fluid'
  3. // select all nodes selected in step 2 and all of their descendants
  4. child::div starting from the nodes selected in step 3, select all children of those nodes that are div elements

So the reason you are getting the same result in both cases is because the div you are locating is a parent of one of the nodes selected in step 3 and a child of one of the nodes selected in step 3.

If you are just trying to select the parent or child of the container-fluid div, then get rid of the double slashes:

//div[@class='container-fluid']/parent::div

//div[@class='container-fluid']/div

The child:: axis is redundant most of the time and can be omitted in this case as I have done above.


推荐阅读