2012-08-14 23 views
14

我正在嘗試查找帶有動態生成ID的元素。字符串的最後一部分是常量(「ReportViewer_fixedTable」),所以我可以使用它來定位元素。我曾嘗試XPath中使用正則表達式:在C中用Selenium查找部分ID的元素

targetElement = driver.FindElement(
    By.XPath("//table[regx:match(@id, "ReportViewer_fixedTable")]")); 

和定位由CssSelector:

targetElement = driver.FindElement(
    By.CssSelector("table[id$='ReportViewer_fixedTable']")); 

無論是作品。任何建議,將不勝感激。

回答

34

這是因爲CSS選擇需要修改你幾乎沒有...

driver.FindElement(By.CssSelector("table[id*='ReportViewer_fixedTable']"))` 

http://sauceio.com/index.php/2010/01/selenium-totw-css-selectors-in-selenium-demystified/

css=a[id^='id_prefix_'] 

id與文本id_prefix_開始的鏈接。

css=a[id$='_id_sufix'] 

id與所述文本_id_sufix結尾的鏈接。

css=a[id*='id_pattern'] 

與包含文本id_patternid的鏈接。

您使用的是我假設的後綴不是您應該使用的部分鏈接文本標識符(除非我看到您的html,這意味着下次嘗試顯示您的html)。儘管如此,*=在任何情況下都是可靠的。

+0

我該如何應用這個做CSS類名的部分匹配?我正在嘗試尋找具有「自定義標籤」類或「可定製標籤」類的標籤元素。 'By.CssSelector(「label [class $ = custom-label」)'似乎不起作用。 我可以只使用By.ClassName兩次並結合結果,但仍想知道如何使用CssSelector實現這一點。 – atlantis 2013-12-16 21:01:59

2

嘗試使用

targetElement = driver.FindElement(By.XPath("//table[contains(@id, "ReportViewer_fixedTable")]")); 

注意這將檢查所有具有ID包含(而不是隻用「ReportViewer_fixedTable」結束)的元素。我會嘗試找到一個正則表達式選項,以更準確地回答你的問題。

+0

並且是一個骯髒的方式將是.//table[substring(@id,字符串長度(@id) - 22)='ReportViewer_fixedTable'] – 2012-08-15 00:32:30

+0

謝謝你,這個伎倆。 – 2012-08-17 22:42:07

0

無論XPath版本如何,此解決方案都可以正常工作。首先,在你的COMMON helper類的某個地方創建一個方法。

public static string GetXpathStringForIdEndsWith(string endStringOfControlId) 
    { 
     return "//*[substring(@id, string-length(@id)- string-length(\"" + endStringOfControlId + "\") + 1)=\"" + endStringOfControlId + "\"]"; 
    } 

在我的情況,下面是在不同的版本我的產品::的控制ID

1.0 :: ContentPlaceHolderDefault_MasterPlaceholder_HomeLoggedOut_7_hylHomeLoginCreateUser

2.0 :: ContentPlaceHolderDefault_MasterPlaceholder_HomeLoggedOut_8_hylHomeLoginCreateUser

然後,你可以調用上面的方法來找到具有靜態結束字符串的控件。

By.XPath(Common.GetXpathStringForIdEndsWith("<End String of the Control Id>")) 

對於其餘爲V1 & V2提到的控制ID的,我使用如下:

By.XPath(Common.GetXpathStringForIdEndsWith("hylHomeLoginCreateUser")) 

整體邏輯的是,可以使用下面的XPath表達式以找到結束的控制與特定的字符串:

//*[substring(@id, string-length(@id)- string-length("<EndString>") + 1)="<EndString>"] 
相關問題