目前,我正在开发一个包含快速js组件的网页。我正在尝试实现将元素从调色板中拖放到网格中,如屏幕截图所示。我从调色板中拖动的元素可以使用其模型ID进行标识。我放下元素的那一刻,就在网格上创建了它的副本,其模型ID发生了变化。在dom中看到的ID也会动态添加。网格中将有多个元素具有与屏幕截图相同的属性。
如何唯一且动态地找到此元素?
我已经尝试过使用Sikuli,但这没有帮助,因为会有多个相似的外观元素。我可以使用findElements()获取网格上的所有元素,但是无法比较最近删除的元素。我要做的就是在将元素放到网格上之后唯一地找到该元素,以便我可以对其进一步执行操作。
我们可以逆转寻找元素的过程吗?从鼠标光标的位置找到元素?
答案 0 :(得分:1)
可以通过两种方法获取最后添加的元素:
从屏幕截图中提到的div结构中,我可以看到属性“ id”正像“ j_57”和“ j_59”一样递增,因此页面上的每个新项目在其后都将有一个id已添加到页面上。
因此,您可以在此处添加ID列表并获取最后一个元素,然后再将其添加到网页上,然后再次获取ID列表并检查最后一个元素,该元素就是您所需要的元素已在页面上添加,您可以通过检查其“ j_”号是否已从最后一个值开始递增来对其进行验证。
如果当前添加的元素被添加到div结构的最后一个元素中,则可以执行拖放操作,并可以使用xpath //g
直接获取最后一个元素。
第1点的代码应为:
//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_递增值来确定新元素。其他第二种方法又短又甜,也可以很好地工作。