获取我通过ID或名称等获得的元素的Xpath字符串.Python硒



我有这个元素,我想通过代码访问它的Xpath,不像find_element(by . Xpath,'myXpath')那样通过Xpath查找元素而不是在浏览器上手动获取xpath

today = driver.find_element(By.CLASS_NAME,'today')
day = today.get_attribute("data-day")
xpathString = today.get_xpath() # <--- this function doesn't exist

可以通过get_attribute()获取元素的属性。函数,但是我找不到返回元素Xpath的函数。

请问这可能吗?提前感谢!

返回类名为today的元素el的完整xpath,即/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)

最新更新