2014-03-27 45 views
0

我想找出一個解決方案,以便使用硒的所有元素在稍後填充測試值。我能夠獲得所有元素,但我想過濾掉那些以字母's'開頭的元素。所以我可以得到像sFirst,sLast,sAddress等元素。我可以使用下面的代碼。但我不確定這裏的'後'應該是什麼。通過使用Selenium以字母開頭來過濾DOM元素

// I am not sure what should be after 's' here. 
List<WebElement> allEle = driver.findElements(By.id("s *")); 

OR

// instead of all elements, need to find ids starting with 's' 
List<WebElement> allEle = driver.findElements(By.cssSelector("*")); 


//iterate and print 
for (WebElement ele : allEle) { 
    ele.getAttribute("id");  // id of each element 
    ele.getText(); 

    System.out.println ("Element :" + ele.getAttribute("id") + ": Test :" +ele.getText()); 

} 

編輯注:增加了對循環結束的代碼塊中括號

回答

2

你可以找到的元素無法與首發如下:

List<WebElement> allEle = driver.findElements(By.cssSelector("*:not([id^='s'])")); 

如果您試圖找到以s開頭的所有元素:

List<WebElement> allEle = driver.findElements(By.cssSelector("[id^='s']")); 

編輯:

篩選出與SA,SB等開始元素,我認爲這會工作:

List<WebElement> allEle = driver.findElements(By.cssSelector("[id^='s']")); 
String letters[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; 
foreach (String letter in letters) 
{ 
    allEle = allEle.findElements(By.cssSelector("*:not([id^='s" + letter + "'])); 
} 

你也可以試試這個,但我認爲這可能是緩慢的:

List<WebElement> allEle = driver.findElements(By.cssSelector("[id^='s']" + 
    ":not([id^='sA']," + 
    "[id^='sB']," + 
    "[id^='sC']," + 
    "[id^='sD']," + 
    "[id^='sE']," + 
    "[id^='sF']," + 
    "[id^='sG']," + 
    "[id^='sH']," + 
    "[id^='sI']," + 
    "[id^='sJ']," + 
    "[id^='sK']," + 
    "[id^='sL']," + 
    "[id^='sM']," + 
    "[id^='sN']," + 
    "[id^='sO']," + 
    "[id^='sP']," + 
    "[id^='sQ']," + 
    "[id^='sR']," + 
    "[id^='sS']," + 
    "[id^='sT']," + 
    "[id^='sU']," + 
    "[id^='sV']," + 
    "[id^='sW']," + 
    "[id^='sX']," + 
    "[id^='sY']," + 
    "[id^='sZ']"))); 
+0

This works,thank you。我試圖過濾出以s +開頭的元素[全部以大寫字母開頭]。我試過這個(「[id^='s [A-Z]']」)),沒有工作。任何建議? – SamK