使用Selenium webdriver从文件系统中拖放文件

3
2个回答

1
很抱歉,WebDriver只能控制浏览器,无法触及浏览器外的任何内容。如果您想要拖放某些东西,您需要使用Robot或其他工具(可能有适用于此的库)。

0

唯一帮助我的是运行我在Selenium: Drag and Drop from file system to webdriver?中找到的JS代码。

只需将整个代码复制粘贴到您的项目中即可。

参见: static void DropFile(IWebElement target, string filePath, 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));

2
你能在你的帖子中添加更多内容吗?如果你提供的链接发生变化,你的回答就不再有帮助了。 - dckuehn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接