Selenium: Upload file in Google Chrome

2020-03-01 20:02发布

问题:

Is there any way to upload file in Google Chrome since Selenium RC "attach_file" only supports *Firefox? Any suggestion or workarounds are much appreciated.

回答1:

If you are using Webdriver then to upload file all you need is use "sendKeys" to type the file path. You need to 'skip' the part of clicking on the browse button that opens a dialog box to select the file. A Java version that works for me looks something like below,

WebElement inputFilePath = driver.findElement(By.id("filepath"));
inputFilePath.sendKeys("/absolute/path/to/my/local/file");


回答2:

Uploading file is usually a POST request, so you actually can upload a file without using Selenium; Unless your site requires cookies, then you need to reconstruct the cookies with webdriver.get_cookies() first

A simple example:

# required package:
#   http://pypi.python.org/pypi/MultipartPostHandler/0.1.0

import MultipartPostHandler, urllib2, cookielib

cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),
                              MultipartPostHandler.MultipartPostHandler)

path_to_file = r"abc.zip"

open_file = open(path_to_file,"rb")
param = { "file": open_file }
req = opener.open("http://www.yoursite.com/uploadfile", param)
open_file.close()


回答3:

Using IJavaScriptExecutor is to change the upload input field to click able so chrome driver won't pop-up error saying this element is non clickable.

        [SetUp]
        public void SetupTest()
        {
            driver = new ChromeDriver();
            baseURL = "";
            verificationErrors = new StringBuilder();
        }

        [Test]
        public void Test()
        {
            IJavaScriptExecutor js = driver as IJavaScriptExecutor;
            IWebElement element = driver.FindElement(By.Id("UploadFile_ButtonID"));
            js.ExecuteScript("arguments[0].style.visibility = 'visible'; arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0].style.opacity = 1", element);
            Thread.Sleep(1000);
            element.SendKeys("D:\\path\\test\\image.jpg");
}