当我使用IEDriver
执行我的脚本而没有兼容性视图时,我的测试脚本运行没有任何问题。
但是,如果我在兼容性视图中添加域后执行相同的脚本,则找不到某些元素,并且我得到例外。
e.g。 我想从这个DOM中获取所选项目的文本:
<select id="selectNumber" name="selectNumber" style="width:180px;">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
我正在使用XPath .//*[@id='selectNumber']/option[@selected='selected']
获取文本,但它不起作用。
我刚刚检查过,在我手动更改文档版本之前,IE中没有为所选选项显示selected="selected"
。
答案 0 :(得分:2)
您可以使用适用于所有浏览器的Select
类。这是一些代码
Select sel = new Select(driver.findElement(By.id("selectNumber")));
WebElement selectOption = sel.getFirstSelectedOption();
String text = selectOption.getText();
答案 1 :(得分:0)
我认为您应该考虑从使用XPath
更改为使用cssSelector
。找到元素更安全,而不是依赖于整个&#34;路径&#34;。使用cssSelector
与IEDriver
一起运行时(如您在问题中所述),它很有可能不会中断。
你可以用两者实现相同的目标,但是当你使用XPath时,你的DOM对变化更加明智,并且你有更大的机会在页面更改后看到测试被破坏。
对于您的情况,您可以通过两种方式使用它:
XPath(因为你必须拥有它)
driver.findElement(By.xpath(".//*[@id='selectNumber']/option[@selected='selected']"))
<强>选择强>
driver.findElement(By.cssSelector("#selectNumber[selected]"))
当你有更复杂的&#34;路径&#34;你可以在cssSelectors中组合更多类似CSS类的东西。例如(当你没有身份证时):
<select class"nice-dropdown" name="selectNumber" style="width:180px;">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
driver.findElement(By.cssSelector("select.nice-dropdown"))
(返回select元素)
driver.findElement(By.cssSelector("select.nice-dropdown option[value='3']"))
(返回值为3的选项)
使用selectors
您有更短的&#34;路径&#34;。它们的工作方式与在CSS中使用选择器的方式相同。
作为参考:
希望这些信息在某种程度上有所帮助。