如何在Selenium中对这个可拖动列表进行排序



练习链接https://demoqa.com/sortable

我试过这个代码

Actions action=new Actions(driver);
List<WebElement> elements=driver.findElements(By.xpath("//*[@id="demo-tabpane-list"]/div/div"));
for(int i=5;i>=0;i--) {

action.dragAndDrop(elements.get(0), elements.get(i)).build().perform();
}
List<WebElement> list = driver.findElements(By.xpath("//* [@id='demo-tabpane-list']/div/div"));

for(int i =1;i<list.size();i++) {

WebElement element = driver.findElement(By.xpath("//*[@id='demo-tabpane-list']/div/div["+ i +"]"));

WebElement destination6 = driver.findElement(By.xpath("//*[@id='demo-tabpane-list']/div/div[6]"));
WebElement destination5 = driver.findElement(By.xpath("//*[@id='demo-tabpane-list']/div/div[5]"));
WebElement destination4 = driver.findElement(By.xpath("//*[@id='demo-tabpane-list']/div/div[4]"));
WebElement destination3 = driver.findElement(By.xpath("//*[@id='demo-tabpane-list']/div/div[3]"));
WebElement destination2 = driver.findElement(By.xpath("//*[@id='demo-tabpane-list']/div/div[2]"));
WebElement destination1 = driver.findElement(By.xpath("//*[@id='demo-tabpane-list']/div/div[1]"));

Actions action = new Actions(driver);

if(element!=null) {
action.dragAndDrop(element, destination6).perform();
action.dragAndDrop(element, destination5).perform();
action.dragAndDrop(element, destination4).perform();
action.dragAndDrop(element, destination3).perform();
action.dragAndDrop(element, destination2).perform();
action.dragAndDrop(element, destination1).perform();
break;
}
}
Please enhance it as per your need.

为了对元素进行排序,需要获取每个元素并将其拖动到目的地。

下面的解决方案基本上将每个可排序元素拖放到表上方(尽管这使用了C#,但我认为逻辑可以在Java中使用(。在这种情况下,我将目的地设置为列表选项卡,以确保元素位于列表上方。原因:当我试着把它设置在第一排时,它会转到第二排。

逻辑如下

  • 将元件2拖放到1 以上

  • 2 上方的拖放元件3

  • 拖放元件4高于3

  • 拖放元件5高于4

  • 拖放元件6高于5

    // Function to sort the elements
    public void SortElements()
    {
    var action = new Actions(webDriver);
    action.DragAndDrop(sortablePage.GetSortableElementByIndex(2), sortablePage.GetListTab()).Perform();
    action.DragAndDrop(sortablePage.GetSortableElementByIndex(3), sortablePage.GetListTab()).Perform();
    action.DragAndDrop(sortablePage.GetSortableElementByIndex(4), sortablePage.GetListTab()).Perform();
    action.DragAndDrop(sortablePage.GetSortableElementByIndex(5), sortablePage.GetListTab()).Perform();
    action.DragAndDrop(sortablePage.GetSortableElementByIndex(6), sortablePage.GetListTab()).Perform();
    }
    // Create a method to get the sortable element by index
    public IWebElement GetSortableElementByIndex(int index)
    {
    return WaitForElementByXPath(wait, $"//div[@id='demo-tabpane-list']/div/div[{index}]");
    }
    // Create a method to get the Tab above the list
    public IWebElement GetListTab()
    {
    return WaitForElementById(wait, $"demo-tab-list");
    }
    

如果您想查看C#代码的更多详细信息,可以参考以下内容:https://github.com/lorvindc/web-ui-specflow-framework

最新更新