0

I have one xpath based on class and I'm trying to find the parent element of it from the current.

Path 1

/html/body/div[2]/div[2]/div/div[2]/div/div[2]/div[2]/div[1]/div/div/p[8]/b[2]/a

Path 2

/html/body/div[2]/div[2]/div/div[2]/div/div[2]/div[2]/div[1]/div/div/p[8]/b[2]

Path 1 can also represent using class name i.e. "xyz" driver.find_element_by_xpath('//a[@class="xyz"]')

How can I traverse to parent node from the current node ?

NarendraR
  • 7,577
  • 10
  • 44
  • 82
BalB
  • 1
  • 1
  • 1
    This sounds like an [X-Y problem](http://xyproblem.info/). Instead of asking for help with your solution to the problem, edit your question and ask about the actual problem. What are you trying to do? – undetected Selenium Jul 10 '20 at 04:44
  • 1
    Does this answer solves your query? https://stackoverflow.com/questions/18079765/how-to-find-parent-elements-by-python-webdriver – Sajid Jul 10 '20 at 04:46

2 Answers2

0

Answer to the question How can i traverse to parent node from the current node is:

  1. Use /.. in your xpath. e.g. //a[@class="xyz"]/.. - this will locate immediate parent of a[@class="xyz"]

  2. /parent::* or /parent::<tagname> - your xpath code should be //a[@class="xyz"]/parent::*

NarendraR
  • 7,577
  • 10
  • 44
  • 82
  • How about getting (printing) html tags inside the current node? – BalB Jul 11 '20 at 13:24
  • @BalB, Means ? what do you want to achieve ? If you are tying to print tag inside current node, it will print all child tags not parent. – NarendraR Jul 11 '20 at 13:53
0

Due to XPath documentation, here is several options you could use:

//a[@class="xyz"]/parent::tagname - It will select only the parent element of the current node

//a[@class="xyz"]/ancestor::tagname - Give's you all ancestors (parents, grandparents, etc.) of the current node

//a[@class="xyz"]/preciding-sibling::tagname - Selects all siblings before the current node

Alex
  • 798
  • 1
  • 8
  • 21