【问题标题】:How to find an new element recently added on webpage dynamically after drag and drop in selenium?在 selenium 中拖放后如何动态查找最近添加到网页上的新元素?
【发布时间】:2019-02-06 09:52:32
【问题描述】:

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

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

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

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

【问题讨论】:

  • 已回答,请检查并告诉我是否有效。
  • 嗨@user765,在拖放之后,副本会在哪里创建——它总是在最后还是介于两者之间?
  • @AliCSE 我将 x,y 坐标传递给拖放方法
  • 好的,我问的是html源代码。总是在最后创建新的model-id

标签: java selenium selenium-webdriver drag-and-drop webdriver


【解决方案1】:

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

  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_ 递增值来确定新元素。第二种方法又短又甜,也可以正常工作。

【讨论】:

  • 是的,请检查一下,如果有帮助,请点赞并接受答案:)
  • @user765 嘿,对你有帮助吗?如果是,请点赞并接受答案。
  • 嘿,是的,谢谢它与 elementList.get(elementList.size()) 一起使用,-1 返回倒数第二个项目。 :)
  • 太棒了!!乐于助人:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
相关资源
最近更新 更多