Selenium Webdriver 2支持字符串匹配()吗?

时间:2013-06-08 14:51:33

标签: xpath selenium selenium-webdriver

亲爱的Selenium Webdriver专家,

我想知道Selenium Webdriver中的字符串匹配方法是否与Java中的以下代码片段一起正常工作:

if (property.findElements(By.xpath("./dl[@class='cN-featDetails']/dd[matches(class,'propertytype type-house']")).size() > 0 ) {    // line 229

以下是第229行读取的xhtml网页:

<dl class="cN-featDetails">
<dt class="proptype">Property type</dt>
<dd id="ctl00_ctl00_Content_Content_SrchResLst_rptResult_ctl01_EliteListingTemplate_ddPropertyType" class="propertytype type-house" title="Property type: House">House</dd>

然而,这导致以下错误:

Address: 28B/171 Gloucester Street, Sydney
Exception in thread "main" org.openqa.selenium.InvalidSelectorException: The given selector ./dl[@class='cN-featDetails']/dd[matches(class,'propertytype type-house'] is either invalid or does not result in a WebElement. The following error occurred:
[InvalidSelectorError] Unable to locate an element with the xpath expression ./dl[@class='cN-featDetails']/dd[matches(class,'propertytype type-house'] because of the following error:
[Exception... "The expression is not a legal expression."  code: "51" nsresult: "0x805b0033 (NS_ERROR_DOM_INVALID_EXPRESSION_ERR)"  location: "

我也试过matches(class,'propertytype.*$']")但没有成功。

班级名称的变化取决于该物业是房屋(类型房屋)还是公寓(类型公寓)......

有关如何在匹配中使用正则表达式的任何建议,以检查此属性类型元素中是否存在值/有效树节点?

此代码段正在查找this URL

我在Windows XP和Linux上使用Selenium 2.25.0,Java 1.7.0_11。 7个平台。

非常感谢您的建议。

2 个答案:

答案 0 :(得分:11)

不幸的是,matches() function is a part of XPath 2.0

WebDriver使用仅支持XPath 1.0的Wicked Good XPath库。

因此,您的XPath表达式是非法的,您应该将其重写为仅使用XPath 1.0中的功能和特性。

我认为您可以简单地用contains()取代matches()电话。也就是说, 被视为通过contains()匹配班级名称的良好做法,因为type-house也会匹配type-houses。此外,如果您匹配propertytype type-house并且类碰巧的顺序不同,则它们将无法匹配。 XPath对类没有任何了解,也不了解CSS中使用的空格分隔列表。有关此问题的更多讨论,请参阅例如this

你应该使用CSS选择器:

dl.cN-featDetails > dd.propertytype.type-house

答案 1 :(得分:-2)

正如您的堆栈描述所示:

  

线程“main”中的异常   org.openqa.selenium.InvalidSelectorException:

您的选择器无效

而不是:

./dl[@class='cN-featDetails']/dd[matches(class,'propertytype type-house']

尝试:

./dl[@class='cN-featDetails']/dd[matches(class,'propertytype type-house')]

(注意额外的括号)

如果浏览器本身没有XPath实现(通常是IE),Selenium将只回退到Wicked Good XPath。所以这应该适用于具有XPath实现的现代浏览器。为了交叉兼容,我建议切换到@Slanec的回答中提到的contains()