gpt4 book ai didi

java - 如何在selenium中拖放后动态查找最近添加到网页上的新元素?

转载 作者:行者123 更新时间:2023-12-02 10:17:50 25 4
gpt4 key购买 nike

enter image description here

目前我正在开发一个包含 rappid js 组件的网页。我试图实现将元素从调色板拖放到网格中,如屏幕截图所示。我从调色板中拖动的元素可以使用其模型 ID 进行识别。当我放下元素的那一刻,它的副本就会在网格上创建,它的模型 ID 就会发生变化。 dom 中看到的 id 也会动态添加。网格上将有多个具有与屏幕截图中所示相同属性的元素。

如何唯一且动态地找到这个元素?

我尝试过使用 Sikuli,但它没有帮助,因为会有多个外观相似的元素。我可以使用 findElements() 获取网格上的所有元素,但无法比较最近删除的元素。我想要实现的就是在将元素放到网格上后唯一地找到该元素,以便我可以进一步对其执行操作。

我们可以逆向查找元素的过程吗?从鼠标光标的位置找到该元素?

enter image description here

最佳答案

有两种方法可以获取最后添加的元素:

  1. 从屏幕截图中提到的 div 结构中,我可以看到属性“id”正在像“j_57”和“j_59”一样递增,因此页面上的每个新项目后面都会有一个 id已添加到页面上。

    因此,您可以在这里做的是,您可以在将元素添加到网页上之前获取 id 列表并获取最后一个元素,然后再次获取 id 列表并检查最后一个元素,该元素将是您要添加的元素。已添加到页面上,您可以通过检查其“j_”数字来验证它是否已从最后一个值增加。

  2. 如果当前添加的元素是添加到div结构的最后一个元素,那么你可以通过拖拽的方式直接使用xpath//g获取最后一个元素。

第一点的代码应该是这样的:

    //Fetch the elements before doing the operation
List<WebElement> elements = driver.findElements(By.xpath("//g[contains(@id,'j_')]"));
// You would be getting the last value present by using getAttribute
String lastElement = elements.get(elements.size()-1).getAttribute("id");

//Perform the drag and drop operation now

//Fetch the elements again
List<WebElement> newElements = driver.findElements(By.xpath("//g[contains(@id,'j_')]"));
// Fetch the id attribute again and verify that the j count has incremented and then you can fetch the last element, which is your new element now
String newLastElement = newElements.get(elements.size()-1).getAttribute("id");
// Your new element can be found using
WebElement requiredElement = newElements.get(elements.size()-1);
String modelId = requiredElement.getAttribute("model-id");

第二点的代码应该是这样的:

    //Perform the drag and drop and then fetch the element list
List<WebElement> elementList = driver.findElements(By.xpath("//g"));
// Fetching the last element in the list
WebElement lastElement = elementList.get(elementList.size()-1);
String modelId = lastElement.getAttribute("model-id");

两种方法都是正确的,如果您的 j_ 值在添加元素时递增,那么您可以通过检查第一种方法中的 j_ 递增值来确定新元素。否则,第二种方法既简短又甜蜜,而且效果也很好。

关于java - 如何在selenium中拖放后动态查找最近添加到网页上的新元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54550695/

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