在這裏咱們是用XPath來標識頁面元素、控件的惟一性node
至於什麼是XPath,能夠自行google。chrome有它算出XPath的功能!打開一個網頁,F12,在彈出的小窗口中選中一個標籤,右鍵,看到「copy XPath」了吧!點下而後粘貼下就知道這元素的標籤的XPath多少了chrome
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 '' } } }