练习链接 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 上方
将元素 3 拖放到 2 上方
将元素 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