gpt4 book ai didi

javascript - 无法使用 javascript 执行 HTML5 拖放以进行 Selenium WebDriver 测试

转载 作者:行者123 更新时间:2023-11-30 17:23:18 26 4
gpt4 key购买 nike

为了实现对 Selenium 测试的拖放,我引用了 http://elementalselenium.com/tips/39-drag-and-drop那里提到使用 javascript(来自 https://gist.github.com/rcorreia/2362544 )来处理拖放。

我按原样实现了它并且它起作用了。但就我而言,我有源元素和目标元素的动态 xpath。为了实现这一点,我尝试使用以下代码:

package org.test.selenium;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class HTML5DragAndDrop {
WebDriver driver = null;

@BeforeClass
public void setUp(){
System.out.println(System.getProperty("user.dir"));
String chromeDriver = System.getProperty("user.dir")+ File.separator + "drivers" + File.separator + "chromedriver.exe";

System.setProperty("webdriver.chrome.driver", chromeDriver);

driver = new ChromeDriver();
driver.get("http://the-internet.herokuapp.com/drag_and_drop");
}

@AfterClass
public void tearDown(){
driver.quit();
}
@Test
public void testDragAndDrop() throws IOException, InterruptedException {
String filePath = "C://dnd.js";
String source = "//div[@id='column-a']";
String target = "//div[@id='column-b']";
StringBuffer buffer = new StringBuffer();
String line;
BufferedReader br = new BufferedReader(new FileReader(filePath));
while((line = br.readLine())!=null)
buffer.append(line);

String javaScript = buffer.toString();

javaScript = javaScript + "$('" + source + "').simulateDragDrop({ dropTarget: '" + target + "'});";
((JavascriptExecutor)driver).executeScript(javaScript);
}
}

但它给出了错误:

org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected identifier

( session 信息:chrome=35.0.1916.153)

但是,如果像下面这样使用源和目标作为 css,它工作得很好:

String source = "#column-a";
String target = "#column-b";

有人可以建议我需要做的更改,以便上面可以使用 xpaths 处理源和目标元素吗?就我而言,我只能使用 xpath,我只能使用 xpath。

最佳答案

你的问题是 JQuery 使用了类似 CSS 的语法。 Xpath 在这种情况下不起作用。

如果您必须使用 Xpath,则必须先将 Xpath 字符串转换为 CSS,然后再将其附加到此 JQuery 字符串中:

javaScript = javaScript + "$('" + source + "').simulateDragDrop({ dropTarget: '" + target + "'});";

如果您只是使用 Xpath 来识别使用 ID 的 div,那么您可以在 Java 中试试这个:

Pattern pattern = Pattern.compile("'(.*?)'");
Matcher matcherSource = pattern.matcher(source);
Matcher matcherTarget = pattern.matcher(target);
String cssSource = "#" + matcherSource.group(1);
String cssTarget = "#" + matcherTarget.group(1);
javaScript = javaScript + "$('" + cssSource + "').simulateDragDrop({ dropTarget: '" + cssTarget + "'});";

关于javascript - 无法使用 javascript 执行 HTML5 拖放以进行 Selenium WebDriver 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24742539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com