用Xpath定位元素的方法总是记不住,经常要翻出各种文档链接参考,干脆把需要用到的内容整到这个笔记中方便查找。
Xpath是在XML文档中定位节点的语言。使用 XPath 的主要原因之一是当想要查找的元素缺少合适的 id 或name属性。XPath定位器可以用来绝对或相对定位缺少id或name属性的元素,也可以是用其他属性进行定位。
< html > < body > < form id ="loginForm" > < input name ="username" type ="text" /> < input name ="password" type ="password" /> < input name ="continue" type ="submit" value ="Login" /> < input name ="continue" type ="button" value ="Clear" /> </ form > </ body > < html >
form元素可以这样定位:
1.绝对定位(最容易受HTML语句改变的影响)
2.HTML中第一个form元素
3.包含属性为id,值为“loginForm"的form元素
username元素可以这样定位:
1.form元素的input子元素中包含属性为name,值为”username“的元素
2.包含属性为id,值为“loginForm"的form元素的第一个input子元素
3.包含属性为name,值为”username“的第一个input元素
Clear按钮可以这样定位:
1.同时包含属性为name,值为”continue“和属性为type,值为”button“的input元素
2.包含属性为id,值为“loginForm"的form元素的第4个input子元素
附Xpath学习链接,参见: http://www.w3school.com.cn/xpath/index.asp
有助于发现元素的Xpath的附加组件有:
Xpath Checker (交互式的 XPath 表达式编辑器)
Firebug (对网页的CSS、HTML和JavaScript进行实时编辑、调试和监控)
XPath Helper (便于提取、编辑和评估网页的Xpath)
英文文档出处,参见 : https://selenium-python.readthedocs.org/en/latest/locating-elements.html