Selenium WebDriver在选择xpath时抛出错误

时间:2013-10-30 22:00:15

标签: java xpath selenium selenium-webdriver

driver.findElement(By.xpath("//input[@type="+"checkbox"+"]/following-sibling:://td[contains(text(),"+"template"+"]"))

我的HTML就像这样

<tr>
<td class="tablecontent">
<input type="checkbox" value="59781" name="templateIds">
</td>`enter code here`
<td class="tablecontent"> test11 </td>
</tr>
  

org.openqa.selenium.InvalidSelectorException:给定的选择器   //输入[@类型=复选框] /以下同胞:: // TD [含有(文本(),模板]   无效或不会导致WebElement。下列   发生错误:InvalidSelectorError:无法找到元素   xpath表达式   //输入[@类型=复选框] /以下同胞:: // TD [含有(文本(),模板]   因为以下错误:[例外......“表达式不是   法律表达。“code:”12“nsresult:”0x805b0033(SyntaxError)“   地点:   “文件:/// C:/Users/sanjdash/AppData/Local/Temp/anonymous3529970525380845680webdriver-profile/extensions/fxdriver@googlecode.com/components/driver_component.js   行:5956“]命令持续时间或超时:72毫秒   有关此错误的文档,请访问:   http://seleniumhq.org/exceptions/invalid_selector_exception.html建立   info:version:'2.37.0',修订版:   'a7c61cbd68657e133ae96672cf995890bad2ee42',时间:'2013-10-18   9时51分02' 秒

3 个答案:

答案 0 :(得分:5)

看起来你的报价搞砸了。在XPath中使用单引号来避免这样的问题。

// if template is the text within your XPath
driver.findElement(By.xpath("//input[@type='checkbox']/following-sibling:://td[contains(text(), 'template']"));

// if template is your variable, then it should be
driver.findElement(By.xpath("//input[@type='checkbox']/following-sibling:://td[contains(text(), " + template + "']"));

另外,请仔细阅读错误,它会告诉您已经需要的足够信息。如您所见,消息中的选择器中没有引号。

  

给定的选择器   //输入[@类型=复选框] /以下同胞:: // TD [含有(文本(),模板]   无效或不会导致WebElement。

答案 1 :(得分:0)

"//input[@type="+"checkbox"+"]/following-sibling:://td[contains(text(),"+"template"+"]"

产生错误的字符串。试试python:

"//input[@type="+"checkbox"+"]/following-sibling:://td[contains(text(),"+"template"+"]"
'//input[@type=checkbox]/following-sibling:://td[contains(text(),template]'

您应该使用引号括起复选框和模板

"//input[@type="checkbox"]/following-sibling:://td[contains(text(),"template"]"

"//input[@type='checkbox']/following-sibling:://td[contains(text(),'template']"

使用

"//input[@type="+"'checkbox'"+"]/following-sibling:://td[contains(text(),"+"'template'"+"]"

"//input[@type='{type}']/following-sibling:://td[contains(text(),'{text}']".format(type='checkbox',text='template')

答案 2 :(得分:0)

您的“包含”功能没有右括号 并需要正确的引用。

如果CHECKBOX和TEMPLATE是字符串,请尝试:

driver.findElement(By.xpath("//input[@type='checkbox']/following-sibling:://td[contains(text(),'template')]"))

如果它们是变量,请尝试:

driver.findElement(By.xpath("//input[@type='" +checkbox+"']/following-sibling:://td[contains(text(),'"+template+"')]"))