xpath定位的集中方法
第一种方法:通过绝对路径做定位(相信大家不会使用这种方式)
By.xpath("html/body/div/form/input")
By.xpath("//input")
第三种方法:通过元素索引定位
By.xpath("//input[4]")
第四种方法:使用xpath属性定位(结合第2、第3中方法可以使用)
By.xpath("//input[@id='kw1']")
By.xpath("//input[@type='name' and @name='kw1']")
第五种方法:使用部分属性值匹配(最强大的方法)
By.xpath("//input[start-with(@id,'nice')
By.xpath("//input[ends-with(@id,'很漂亮')
By.xpath("//input[contains(@id,'那么美')]")
其它相关的一些定位用法
ancestor 选取当前节点的所有先辈(父、祖父等)
//*[@id="content_views"]/p[51]/span[1]/ancestor::div
ancestor-or-self 选取当前节点的所有先辈(父、祖父等)以及当前节点本身(不包含叔叔伯伯
//*[@id="content_views"]/p[51]/span[1]/ancestor-or-self::div
descendant选取当前节点的所有后代元素(子、孙等)
//*[@id="content_views"]/descendant::span
descendant-or-self选取当前节点的所有后代元素(子、孙等)以及当前节点本身
//*[@id="content_views"]/p[51]/descendant-or-self::p
preceding 选取文档中当前节点的开始标签之前的所有节点
//*[@id="content_views"]/p[51]/preceding::p
preceding-sibling选取当前节点之前的所有同级节点
//*[@id="content_views"]/p[51]/span[2]/preceding-sibling::span
following 选取文档中当前节点的结束标签之后的所有节点(包括自己及自己的后代元素
//*[@id="content_views"]/p[51]/following::p
following-sibling选取当前节点之后的所有同级节点
//*[@id="content_views"]/p[51]/span[2]/following-sibling::span
注意这个::后面跟的是对应的父、子、同级等标签
并且xpath还可以通过contain定位到任何属性:
//*[contains(@class, 'Test')]