【发布时间】:2012-06-26 14:10:46
【问题描述】:
我正在测试一个 Web 应用程序,其中一种情况是能够将文件从文件系统中拖放到组件上。
类似这样:
http://s3u.github.com/har-view/
http://html5demos.com/dnd-upload
有没有办法模拟将文件从文件系统拖放到 使用网络驱动程序的元素?
【问题讨论】:
标签: java selenium drag-and-drop webdriver
我正在测试一个 Web 应用程序,其中一种情况是能够将文件从文件系统中拖放到组件上。
类似这样:
http://s3u.github.com/har-view/
http://html5demos.com/dnd-upload
有没有办法模拟将文件从文件系统拖放到 使用网络驱动程序的元素?
【问题讨论】:
标签: java selenium drag-and-drop webdriver
没有。不幸的是,WebDriver 只驱动浏览器,不能触摸它之外的任何东西。如果你想拖放一些东西,你必须使用Robot 或任何其他工具 (there might be a library for this)。
【讨论】:
唯一对我有帮助的是运行我在 Selenium: Drag and Drop from file system to webdriver? 中找到的 JS 代码
只需将整个内容复制粘贴到您的项目中即可。
见: 静态无效 DropFile(IWebElement 目标,字符串文件路径,int offsetX = 0,int offsetY = 0) {
if (String.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException("filePath");
}
if (!File.Exists(filePath))
{
throw new FileNotFoundException(filePath);
}
IWebDriver driver = ((RemoteWebElement)target).WrappedDriver;
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
string JS_DROP_FILE = @"
var target = arguments[0],
offsetX = arguments[1],
offsetY = arguments[2],
document = target.ownerDocument || document,
window = document.defaultView || window;
var input = document.createElement('INPUT');
input.type = 'file';
input.style.display = 'none';
input.onchange = function () {
target.scrollIntoView(true);
var rect = target.getBoundingClientRect(),
x = rect.left + (offsetX || (rect.width >> 1)),
y = rect.top + (offsetY || (rect.height >> 1)),
dataTransfer = { files: this.files };
['dragenter', 'dragover', 'drop'].forEach(function (name) {
var evt = document.createEvent('MouseEvent');
evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);
evt.dataTransfer = dataTransfer;
target.dispatchEvent(evt);
});
setTimeout(function () { document.body.removeChild(input); }, 25);
};
document.body.appendChild(input);
return input;
";
IWebElement input = (IWebElement)jse.ExecuteScript(JS_DROP_FILE, target, offsetX, offsetY);
input.SendKeys(filePath);
wait.Until(ExpectedConditions.StalenessOf(input));
【讨论】: