JAVA – 如何在selenium中使用xpath

我有这个HTML代码:

 «Seleziona la categoria» -- VEICOLI -- Auto  

我必须选择标签option标识的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 

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

您没有正确的XPath语法。 您需要围绕要匹配的文本属性值的引号。 尝试:

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