在 Selenium 中拖放
Drag and drop in Selenium
在 https://www.globalsqa.com/demo-site/draganddrop/ 中,我需要将带有文本“High Tatras”的图片拖放到垃圾箱部分。
@Test
void task1() {
System.setProperty("webdriver.chrome.driver", "C:\Users\DELL\Desktop\New folder\chromedriver.exe");
WebDriver webDriver = new ChromeDriver();
try {
webDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
webDriver.get("https://www.globalsqa.com/demo-site/draganddrop/");
WebElement from = webDriver.findElement(By.xpath("//*[@id=\"gallery\"]/li[1]"));
WebElement to = webDriver.findElement(By.xpath("//*[@id=\"trash\"]"));
Actions actions = new Actions(webDriver);
actions.dragAndDrop(from, to).build().perform();
} finally {
webDriver.close();
}
}
from
和 to
元素都在 iframe
内。
因此,要访问这些元素,您需要先切换到 iframe
。
您的代码将如下所示:
@Test
void task1() {
System.setProperty("webdriver.chrome.driver", "C:\Users\DELL\Desktop\New folder\chromedriver.exe");
WebDriver webDriver = new ChromeDriver();
try {
webDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
webDriver.get("https://www.globalsqa.com/demo-site/draganddrop/");
driver.switchTo().frame(driver.findElement(By.xpath("//div[@rel-title='Photo Manager']//iframe")));
WebElement from = webDriver.findElement(By.xpath("//*[@id='gallery']/li[1]"));
WebElement to = webDriver.findElement(By.xpath("//*[@id='trash']"));
Actions actions = new Actions(webDriver);
actions.dragAndDrop(from, to).build().perform();
} finally {
webDriver.close();
}
}
在 https://www.globalsqa.com/demo-site/draganddrop/ 中,我需要将带有文本“High Tatras”的图片拖放到垃圾箱部分。
@Test
void task1() {
System.setProperty("webdriver.chrome.driver", "C:\Users\DELL\Desktop\New folder\chromedriver.exe");
WebDriver webDriver = new ChromeDriver();
try {
webDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
webDriver.get("https://www.globalsqa.com/demo-site/draganddrop/");
WebElement from = webDriver.findElement(By.xpath("//*[@id=\"gallery\"]/li[1]"));
WebElement to = webDriver.findElement(By.xpath("//*[@id=\"trash\"]"));
Actions actions = new Actions(webDriver);
actions.dragAndDrop(from, to).build().perform();
} finally {
webDriver.close();
}
}
from
和 to
元素都在 iframe
内。
因此,要访问这些元素,您需要先切换到 iframe
。
您的代码将如下所示:
@Test
void task1() {
System.setProperty("webdriver.chrome.driver", "C:\Users\DELL\Desktop\New folder\chromedriver.exe");
WebDriver webDriver = new ChromeDriver();
try {
webDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
webDriver.get("https://www.globalsqa.com/demo-site/draganddrop/");
driver.switchTo().frame(driver.findElement(By.xpath("//div[@rel-title='Photo Manager']//iframe")));
WebElement from = webDriver.findElement(By.xpath("//*[@id='gallery']/li[1]"));
WebElement to = webDriver.findElement(By.xpath("//*[@id='trash']"));
Actions actions = new Actions(webDriver);
actions.dragAndDrop(from, to).build().perform();
} finally {
webDriver.close();
}
}