【问题标题】:How to automate multiple files drag and drop using C# selenium?如何使用 C# selenium 自动拖放多个文件?
【发布时间】:2019-07-20 13:56:24
【问题描述】:

我能够使用以下代码拖放单个图像,但不确定需要更改哪些内容以支持多个文件上传。有人能帮我吗。谢谢。

 driver.Url = "http://example.com";
 IWebElement droparea = driver.FindElementByXPath("//*[@id=\"divDrag\"]");
 DropFile(droparea, @"C:\Backup\ToBeUploaded\Image.png"); //Currently doing one file
 //DropFile(droparea, Directory.GetFiles(@"C:\Backup\ToBeUploaded\")); // Expectation

 const string JS_DROP_FILE = "for(var b=arguments[0],k=arguments[1],l=arguments[2],c=b.ownerDocument,m=0;;){var e=b.getBoundingClientRect(),g=e.left+(k||e.width/2),h=e.top+(l||e.height/2),f=c.elementFromPoint(g,h);if(f&&b.contains(f))break;if(1<++m)throw b=Error('Element not interractable'),b.code=15,b;b.scrollIntoView({behavior:'instant',block:'center',inline:'center'})}var a=c.createElement('INPUT');a.setAttribute('type','file');a.setAttribute('style','position:fixed;z-index:2147483647;left:0;top:0;');a.onchange=function(){var b={effectAllowed:'all',dropEffect:'none',types:['Files'],files:this.files,setData:function(){},getData:function(){},clearData:function(){},setDragImage:function(){}};window.DataTransferItemList&&(b.items=Object.setPrototypeOf([Object.setPrototypeOf({kind:'file',type:this.files[0].type,file:this.files[0],getAsFile:function(){return this.file},getAsString:function(b){var a=new FileReader;a.onload=function(a){b(a.target.result)};a.readAsText(this.file)}},DataTransferItem.prototype)],DataTransferItemList.prototype));Object.setPrototypeOf(b,DataTransfer.prototype);['dragenter','dragover','drop'].forEach(function(a){var d=c.createEvent('DragEvent');d.initMouseEvent(a,!0,!0,c.defaultView,0,0,0,g,h,!1,!1,!1,!1,0,null);Object.setPrototypeOf(d,null);d.dataTransfer=b;Object.setPrototypeOf(d,DragEvent.prototype);f.dispatchEvent(d)});a.parentElement.removeChild(a)};c.documentElement.appendChild(a);a.getBoundingClientRect();return a;";

 static void DropFile(IWebElement target, string filePath, double offsetX = 0, double offsetY = 0)
 {
      if (!File.Exists(filePath))
         throw new FileNotFoundException(filePath);
      IWebDriver driver = ((RemoteWebElement)target).WrappedDriver;
      IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
      IWebElement input = (IWebElement)jse.ExecuteScript(JS_DROP_FILE, taget, offsetX, offsetY);
      input.SendKeys(filePath);
 }

【问题讨论】:

  • 为什么不循环运行这个函数?
  • 由于某种原因,它不能那样工作,我可以通过刷新并重试来处理多个文件。但是,在某些网页中,URL 会丢失。有没有其他办法?

标签: javascript c# selenium-webdriver file-upload


【解决方案1】:

在下面的代码中

文件地址出现在“fileLoc”部分。 您可以使用“fileLoc”上传图片。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApp4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.AllowDrop = true;
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] filePaths = (string[])(e.Data.GetData(DataFormats.FileDrop));
                foreach (string fileLoc in filePaths)
                {
                    // Code to read the contents of the text file
                    if (File.Exists(fileLoc))
                    {
                        using (TextReader tr = new StreamReader(fileLoc))
                        {
                            MessageBox.Show(tr.ReadToEnd());
                        }
                    }

                }
            }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }


    }
}

【讨论】:

  • 我并不想加入我的 C# 应用程序。我正在尝试访问一个 URL 并放在那里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 2023-03-03
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多