在这里我们是用XPath来标识页面元素、控件的唯一性
XPath
至于什么是XPath,可以自行google。chrome有它算出XPath的功能!打开一个网页,F12,在弹出的小窗口中选中一个标签,右键,看到“copy XPath”了吧!点下然后粘贴下就知道这元素的标签的XPath多少了
Javascript get XPath and find element by XPath
Chrome浏览器中通过js获取xpath和根据xpath获取元素
export default {
getXPath(elm){
let allNodes = document.getElementsByTagName('*')
for(var segs = []; elm && elm.nodeType == 1; elm = elm.parentNode){
if(elm.hasAttribute('id')){
let uniqueIdCount = 0
for(var n=0;n < allNodes.length;n++){
if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++;
if (uniqueIdCount > 1) break;
}
if(uniqueIdCount == 1){
segs.unshift('//*[@id="' + elm.getAttribute('id') + '"]');
return segs.join('/');
}else{
return false
}
}else{
for(var i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling){
if (sib.localName == elm.localName) i++;
}
if(i == 1){
if(elm.nextElementSibling){
if(elm.nextElementSibling.localName != elm.localName){
segs.unshift(elm.localName.toLowerCase())
}else{
segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
}
}else{
segs.unshift(elm.localName.toLowerCase())
}
}else{
segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
}
}
}
return segs.length ? '/' + segs.join('/') : null
},
getElem(path){
try{
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate(path, document.documentElement, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result.singleNodeValue || '';
}catch(e){
return ''
}
}
}