how does selenium webdriver upload files to the br

2019-02-03 00:16发布

I am a javascript/java developer and I have been trying to figure out how the selenium webdriver automation framework uploads files from the file system. It is impossible to set a file input via javascript because it is a security violation. Yet somehow webdriver is able to do this with the following command:

driver.setFileDetector(new LocalFileDetector());
WebElement upload = driver.findElement(By.id("myfile"));
upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg");
driver.findElement(By.id("submit")).click();

So they are setting the value by sending keys to it? I don't get it. I have looked through the source code found here: http://code.google.com/p/selenium/source/checkout I am still not able to find where they do this.

Edit: My question is not how to do this with selenium, but how did the selenium developers make this possible? How did they get around the security restrictions in javascript? How are they uploading the file?

6条回答
聊天终结者
2楼-- · 2019-02-03 00:44

In some cases specially with Java you need to create a File object and pass the absolutePath() to the Driver, like the following:

File file = new File(sampleFile);
driver.findElement(By.id("<Your input tag with type of File>")).sendKeys(file.getAbsolutePath());

Sample file is a string that point to the file that needs to be uploaded. This works for me in Firefox and Chrome.

查看更多
趁早两清
3楼-- · 2019-02-03 00:46

I have Uploaded photo on Facebook Using Selenium Webdriver and AutoIt

Steps are as below

Step 1

On eclipse code Upto (Upload a Photo) is as below:

WebElement Upload = Firefox.findElement(By.cssSelector("input[id^='u_']"));
Upload.click();

Step 2

Downloaded and install AutoIt: http://www.autoitscript.com/site/autoit/downloads/ (Download ZIP)

Step 3

Write the code as below in notepad and saved it as PhotoUpload.au3

WinWaitActive("File Upload")
Send("D:\Photo0116.jpg")   
Send("{ENTER}")

Step 4: Right click on this .au3 File & compile it.

Step 5: Add code in script file as below:

try {
    String[] commands = new String[]{};
    // Location of the autoit executable
    commands = new String[] {"D:\\My softwares\\install software\\selenium\\UploadPhoto3.exe"};
    Runtime.getRuntime().exec(commands);
}       
catch (IOException e) {}

Step 6: Run script (PhotoUpload.java)

Step 7: Photo get uploaded successfully.

查看更多
时光不老,我们不散
4楼-- · 2019-02-03 00:51

The upload windowns file function HTML codes are:

<input id="fileField" type="file" onchange="document.getElementById('textfield').value=this.value" name="position">   

<input type="submit" value="导入">

You can use the following codes to finishing uploading a windows file. It works sucessfully and the codes don't include clicking a upload action.

driver.FileDetector = new LocalFileDetector();
FindElement(By.Id("fileField")).SendKeys(@"C:\Users\admin\Desktop\ProfessionCodes.txt"); FindElement(By.CssSelector("input[type='submit']")).Click();
查看更多
Melony?
5楼-- · 2019-02-03 01:00
  //assuming driver is a healthy WebDriver instance
    WebElement fileInput = driver.findElement(By.name("uploadfile"));
   fileInput.sendKeys("C:/path/to/file.jpg");

or

 driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");

Try this and let me know

查看更多
smile是对你的礼貌
6楼-- · 2019-02-03 01:08

Nice question buddy...they have written a HTTP proxy to solve the Javascript secuirty restrictions. Using this proxy made it possible to side-step many of the constraints of the "same host origin" policy, where a browser won't allow Javascript to make calls to anything other than the server from which the current page has been served.

Moreover WebDriver uses the alternative approach of firing events at the OS level. As these "native events" aren't generated by the browser this approach circumvents the security restrictions placed on synthesized events and, because they are OS specific, once they are working for one browser on a particular platform reusing the code in another browser is relatively easy.

Most of the content above is referenced from the below..do read the following reference for more details on Selenium internals

http://www.aosabook.org/en/selenium.html

查看更多
我命由我不由天
7楼-- · 2019-02-03 01:08

This helped me to do file upload,

Code :

 public class FileUpload {
        @Test
        public void test() {
            WebDriver driver = new FirefoxDriver();
            driver.get("http://www.freepdfconvert.com/pdf-word");
            driver.findElement(By.id("clientUpload")).click();
            driver.switchTo()
                    .activeElement()
                    .sendKeys(
                            "/home/likewise-open/GLOBAL/123/Documents/filename.txt");
            driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
            driver.findElement(By.id("convertButton"));
            /*
             * driver.switchTo().activeElement()
             * .sendKeys("selenium_2_testing_tools.pdf"); ;
             */
         {
                driver.wait(30000);
            } catch (Exception er) {
                System.out.println(er);
            }

        }
    }
查看更多
登录 后发表回答