2

I want to know if it's possible to get the XPATH of the web element?

test = driver.find_elements_by_css_selector('div.menu-listes ul.menu.menu-horizontal.menu_left li h3')

for t in test:
    //i want to have the XPATH 

i tried t.location but i get just {'y': 0, 'x': 0}

parik
  • 2,313
  • 12
  • 39
  • 67
  • Why don't you just find the xpath itself instead of using css selector? – Jason Jun 30 '16 at 15:09
  • it's just an example, i want to if it's POSSIBLE to get xpath of the web element or not – parik Jun 30 '16 at 15:10
  • you should rather put html tag here? are you trying to find xpath from a css locator? – abhijeet kanade Jun 30 '16 at 15:37
  • @RemcoW thanks, i searched before posting but i didn't see that question, however the answer is in JAVA, i need it in Python – parik Jun 30 '16 at 15:38
  • @abhijeetkanade No, i try to find xpath from web element – parik Jun 30 '16 at 15:39
  • @abhijeetkanade In Python it's pretty much the same. I've made an answer that literally translates the answer from the duplicate to python and implemented it in your code block. I haven't tested it. – RemcoW Jun 30 '16 at 15:47

2 Answers2

4

The answer from the duplicate question in Python (untested):

test = driver.find_elements_by_css_selector('div.menu-listes ul.menu.menu-horizontal.menu_left li h3')

for t in test:
    driver.execute_script("""gPt=function(c){
                                 if(c.id!==''){
                                     return'id("'+c.id+'")'
                                 } 
                                 if(c===document.body){
                                     return c.tagName
                                 }
                                 var a=0;
                                 var e=c.parentNode.childNodes;
                                 for(var b=0;b<e.length;b++){
                                     var d=e[b];
                                     if(d===c){
                                         return gPt(c.parentNode)+'/'+c.tagName+'['+(a+1)+']'
                                     }
                                     if(d.nodeType===1&&d.tagName===c.tagName){
                                         a++
                                     }
                                 }
                             };
                             return gPt(arguments[0]).toLowerCase();""", t)
Community
  • 1
  • 1
RemcoW
  • 4,196
  • 1
  • 22
  • 37
0

Not really. xpath's aren't unique and if it did automatically get it, it probably won't be that efficient and robust of an xpath (for example, inspect element and check out the xpaths that Google Chrome gives you. They're usually something like div[1]/div[2]/div/div .. etc)

If you don't care about the fact that you might have a bad xpath you can write a function that keeps on getting parent until you reach the root all while keeping track of the path to the element you selected.

Jason
  • 86
  • 1
  • 9