I have this element and I want to access its Xpath by code, not find element by Xpath like find_element(By.XPATH,'myXpath') and not get xpath it manually on the browser
today = driver.find_element(By.CLASS_NAME,'today')
day = today.get_attribute("data-day")
xpathString = today.get_xpath() # <--- this function doesn't exist
we can get the attribute of an element by get_attribute() function, but I couldn't find the function that returns the Xpath of the element.
please is it possible? thanks in advance!
CodePudding user response:
This return the full xpath of the element el
whose class name is today
, i.e. /html/.../el
xpathString = driver.execute_script("""
var el = arguments[0];
aPath ="";
while (el.tagName!='HTML'){
parentEle=el.parentNode;
if(parentEle.querySelectorAll(el.tagName).length>1){
childIndex = 0;
parentEle.querySelectorAll(el.tagName).forEach(function(cEle){
childIndex= childIndex 1;
if(cEle === el){
aPath = el.tagName "[" childIndex "]" "/" aPath;
}
})
}else{
aPath = el.tagName "/" aPath;
}
el=el.parentNode;
}
return "/html/" aPath.substring(0,aPath.length-1).toLowerCase();
""", today)