2014-08-28 31 views
0

我試圖用正則表達式來匹配包含在原本老套的字符串中間的不可預知號碼的ID,一個例子:問題硒匹配通過XPath定位格

<div id="type-84289-model" class="vehicle"> 

我已經試過各種東西,但它似乎最明顯應該工作是:

By.xpath("//div[matches(@id, 'type-.+-model')]")); 

但是,沒有找到該元素。任何人都可以指向正確的方向。

+1

是它的XPath 2?我認爲XPath 1不支持正則表達式。 – 2014-08-28 20:38:07

+0

如果@curiosu正確,你可以嘗試'[starts-with(@id,'type-')並以(@id,'-model')]結尾。 – CiaPan 2014-08-28 20:44:39

+0

我相信它支持Xpath 2.根據我對Selenium的理解,它歸結爲您測試的任何瀏覽器都支持並且我一直使用Firefox 31.0。然而,我曾嘗試使用@Ciapan建議的'starts-with'和'ends-with',但沒有運氣......我得到一個InvalidSelectorException異常。 – Axl 2014-08-28 21:15:37

回答

2

你可以找到的元素,使用以下XPath:

driver.findElement(By.Xpath("//div[contains(@id, 'type-')][contains(@id, '-model')][@class='vehicle']")) 
+0

我至少會把第一個'contains()'改成'starts-with()'。它的可讀性好,不太可能產生誤報,並且可能更快。 – LarsH 2014-08-29 15:17:44

1

curiosu是正確的,XPath的1不支持正則表達式,而且硒不支持的XPath 2. :-(

正如你指出的那樣,ends-with()不XPath 1.0中存在。所以我們可以適應CiaPan的回答如下:

By.xpath("//div[starts-with(@id, 'type-') and 
    substring(@id, string-length(@id)-6) = '-model']")); 
+1

這樣做可以匹配我的div id,但我將@German Petrov's標記爲答案,因爲它會更容易閱讀代碼,並且有很多div可以匹配。感謝您的幫助,這對硒和xpath來說絕對是一次很好的學習體驗! – Axl 2014-08-29 15:02:11

0

萬一ID總是以字符串連字符後跟數字結尾且以開始用連字符的字符串結束的開始這可能是工作:

//div[ contains (translate(@id, '1234567890',''),'--')] 

所以你的情況

By.xpath("//div[ contains (translate(@id, '1234567890',''),'--')]"); 
0

你認真想使用XPath和XPath定位元素?如果沒有,你只是想找到格,那麼你可以使用下一個選擇:如果你需要找到一個仍然匹配模式type-...-model您可以使用CSS選擇該div

driver.findElement(By.Css(".vehicle")); 
//or 
driver.findElement(By.Css("div[class='vehicle']")); 

UDPATE 。但據我所知CSS選擇器不支持正則表達式,所以你可以使用starts/ends with attributes:水木清華這樣的:

//find all divs which id starts with type 
driver.findElement(By.Css("div[class^='type']")) 
//find all divs which id ends with model 
driver.findElement(By.Css("div[class$='model']")) 
//find all divs which id starts with type and ends with model 
driver.findElement(By.Css("div[class^='type'][class$='model']")) 

現在應該工作。

+0

他需要找到一個id與'type-'...'-model'匹配的div。 – LarsH 2014-08-29 01:35:46