gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:00:41 25 4
gpt4 key购买 nike

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

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

或者

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

}

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

最佳答案

您可以按如下方式查找不以 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']")));

关于java - 使用 Selenium 按以字母开头的 id 过滤 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22701179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com