使用Selenium以字母开头的id过滤DOM元素

时间:2014-03-27 23:15:05

标签: java selenium

我正在尝试找到一个解决方案,以便使用selenium获取页面的所有元素,以便稍后填充测试值。我能够获得所有元素,但我想过滤掉那些以字母开头的元素'。所以我可以获得像sFirst,sLast,sAddress等元素。我可以使用下面的代码。但我不确定应该追求什么呢?'这里。

// 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());

}

编辑注释:在代码块内添加了循环结束括号

1 个答案:

答案 0 :(得分:2)

您可以找到不以s开头的元素,如下所示:

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']")));