java - 有什么办法可以解决排序网页元素?使用拖放功能进行排序时遇到困难
问题描述
有什么办法可以解决排序网页元素?使用拖放功能进行排序时遇到困难。我的拖放不起作用,我认为我的逻辑很好,但是在运行代码时没有任何反应......
public void sortable() { // loop for drag and drop is not working...
try {
driver.get("http://jqueryui.com/");
myLibrary.clickButton(By.partialLinkText("Sortable"));
WebElement iframe = driver.findElement(By.xpath("//*[@id='content']/iframe"));
driver.switchTo().frame(iframe);
String temp = "";
Thread.sleep(10 * 1000); //manual work to disorder sortable list prior to start for loop.
Actions action = new Actions(driver);
int i = 1, j = 1;
for (i = 1; i < 8; i = i + 1) {
WebElement sourceText = driver.findElement(By.cssSelector("#sortable > li:nth-child(" + i + ")"));
WebElement dragElement = driver
.findElement(By.cssSelector("#sortable > li:nth-child(" + i + ") > span"));
while (true) {
temp = "Item" + " " + j;
if (temp == sourceText.getText()) {
WebElement targetElement = driver
.findElement(By.cssSelector("#sortable > li:nth-child(" + j + ")"));
action.moveToElement(dragElement).dragAndDrop(dragElement, targetElement).build().perform();
Thread.sleep(1 * 1000);
break;
} else {
if (j == 8) {
break;
} else {
j++;
}
}
}
}
Thread.sleep(5 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
解决方案
基于@JeffC 作为答案发布的内容,这是另一个相同的变体,它使用了 Java 的一些内置功能。
我们基本上使用List.sort()
and aComparator
来完成这项工作。
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SorterSample {
private RemoteWebDriver driver;
@BeforeClass
public void setup() {
driver = new ChromeDriver();
}
@AfterClass
public void cleanup() {
if (driver != null) {
driver.quit();
}
}
@Test
public void testMethod() {
String url = "http://jqueryui.com/sortable/";
driver.get(url);
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe.demo-frame")));
List<WebElement> items = driver.findElements(By.cssSelector("#sortable > li"));
items.sort(
(o1, o2) -> {
int compareValue = o1.getText().compareTo(o2.getText());
if (compareValue < 0) {
new Actions(driver).dragAndDrop(o1, o2).perform();
}
return compareValue;
});
}
}
推荐阅读
- firebase - 我正在编辑 codelabs 友好的聊天应用程序网络。我不想要登录功能如何删除它
- html - 为什么我的 html 表格中没有显示水平滚动?
- mongodb-realm - Auth0 在 MongoDB 领域函数中不起作用
- next.js - Next JS 和服务器端渲染的动态路由
- go - 使用 Bazel 构建 Go 无法解析存储库
- python - 异步方法的 Python 覆盖率
- sql - 遍历整个表,并将满足内部查询的所有值传递给外部查询
- java - 在 logback 中记录的消息前面有空格
- javascript - 是否有正则表达式可以删除字符串中逗号后的所有内容,除了第一个字母
- amazon-dynamodb - Dynamo DB 中大小为 N 的随机抽样,无需全表扫描