我有這個元素,我想通過代碼訪問它的 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 的函式。
請問有可能嗎?提前致謝!
uj5u.com熱心網友回復:
el這將回傳其類名為的元素的完整 xpath today,即/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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/478022.html
