使用XPath选择DOM元素

xiaoxiao2021-02-28  91

在自动化UI测试中, 我们需要找到页面中某个元素进行操作,如单击表单中的某个按钮。我们可以使用测试工具来选择我们想要操作的元素(如intern提供了如 remote.findByCssSelector, remote.findById等等),其中一个方法为remote.findByXpath. 我们可以根据Xpath来选择我们想要定位的元素。 为了确定所使用的Xpath是否正确,我们可以在浏览器的console调试页面中测试。 下面简单介绍下使用document.evaluate来测试我们所写的XPath表达是否正确, (IE截止到ie 11还不支持该方法 document.evaluate, 不过较新的Firefor和chrome是支持的。) 函数签名及参数请参数 document.evaluate

如我们有如下页面结构

<div class="outer"> <div class="inner"> <button>Create</button> </div> </div> <div> <div class="test"> <button>Create</button> </div> </div>

需求是找到文本内容为”Create”且父元素的class为”test”, 于是我们想到如下XPath

//button[parent::div[@class='test']][.='Create']

那么这个表达式能不能找到我们想定位的元素呢。

测试如下代码如下:

snapshot = document.evaluate ( "//button[parent::div[@class='test']][.='Create']", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); console.log(snapshot.snapshotLength) // 输出结果为 1, 即证明所使用的XPath正确。

当然下面测试代码也是可以的

buttonCount = document.evaluate( "count(//button[parent::div[@class='test']][.='Create'])", document, null, XPathResult.ANY_TYPE, null); console.log(buttonCount.numberValue) //结果为 1

参数文章 XPath Tutorial XPath Examples

转载请注明原文地址: https://www.6miu.com/read-53248.html

最新回复(0)