定位元素時,一般用xpath或css selector來定位,定位時可以藉助chrome瀏覽器或firefox瀏覽器的firebug來直接copy selector或copy xpath。此文介紹使用chrome怎樣去驗證css selector或xpath的有效性。
步驟
1. 按F12打開chrome的開發者工具;
2. 再按Esc鍵調出console
經過這倆步驟,chrome的Elements和Console展示在同一個窗口,便於查看。
$(selector)和$$(selector)
可見:前者會列出與selector匹配的所有元素,而後者則是把這些匹配到的元素組成了數組。(點擊返回的每個元素,則會定位到頁面中的img元素及html中的具體位置)
另外還有兩種方法與上面類似:
document.querySelector()會返回DOM中匹配的第一個元素(只返回一個元素);
document.querySelectorAll()等同於$$(selector)
綜上:使用$(selector)即可滿足驗證css selector是否有效的需求
$x(path)
$x(path)返回的是一個數組,數組中即爲與xpath匹配的所有元素。
References:
https://developers.google.cn/web/tools/chrome-devtools/console/command-line-reference?hl=zh-cn
https://getfirebug.com/wiki/index.php/Command_Line_API