6

我有这个 html 代码:

<select name="category" id="category">
    <option value="0">&laquo;Seleziona la categoria&raquo;</option>
    <option value='1' style='background-color:#ddd' disabled="disabled" id='cat1' >-- VEICOLI --</option>
    <option value='2'  id='cat2' >Auto</option>
</select>

我必须选择由option带有 text的标签标识的 WebElement Auto。我尝试了一些解决方案,例如:

d.findElement(By.xpath("/select[@id=category]/option[@id=cat2]")).click();
d.findElement(By.xpath("/select[@id=category]/option[text()='Auto']")).click();
d.findElement(By.xpath("//select[@id=category]/option[Auto]")).click();

但每个人都给我:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"/select[@id=category]/option[@id=cat2]"} ( and other xpath i tried)
Command duration or timeout: 1.52 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html

什么是正确的语法?有人能帮我吗?

4

1 回答 1

16

您的 XPath 语法不正确。您需要在要匹配的文本属性值周围加上引号。尝试:

d.findElement(By.xpath("//select[@id='category']/option[@id='cat2']")).click();
于 2012-05-12T20:08:01.593 回答