Selenium webdriver java - upload file with phantomjs driver

China☆狼群 提交于 2019-12-25 01:01:05

问题


I am running a selenium webdriver script headless using Phantomjs Driver. I am having issues uploading a file though since on a normal browser (firefox or chrome) it would pop up the OS dialog box that would allow me to locate the file in my machine and upload it. How to do that with the ghostDriver (Phantomjs Driver)? Thanks


回答1:


Always identify & interact with elements of type "file" when uploads are concerned. This would solve your issue of pop ups.

Ex: In my application, upload related elements have the below DOM -

<a id="uploadFileButtonLink" class="uploadFileButtonLink" href="javascript:void(0)" data-uidsfdc="3" style="display: none;">Upload a file</a>
<input id="multiFileInput" class="multifile-upload-input-button" type="file" name="chatterFile_upload" multiple="multiple"/>
<input id="multiUploadBtn" class="btnImportant" type="button" value="Upload Files"/>

In this case, you can use sendKeys method to "multiFileInput" which is of type "file". This way it would work for all FF, Chrome & also headless browsers.




回答2:


I am having the same issue and have posted a question for the same. PhantomJS hangs up when using sendKeys() method.

They have an issue logged here - https://github.com/ariya/phantomjs/issues/10993

One of the comments on the issue stated that the below statement worked -

(PhantomJSDriver) driver.executePhantomJS("var page = this; page.uploadFile('input[type=file]', 'path to file');");

You may try the above solution, but it may or may not work.




回答3:


This code helped me with uploading if 'multiple' attribute was set:

protected void uploadFile(CharSequence... keys) {
    if (((WrapsDriver) driver).getWrappedDriver() instanceof PhantomJSDriver) {
        StringBuffer s = new StringBuffer(keys.length);
        for (int index = 0; index < keys.length; index++) {
            s.append(keys[index].toString());
        }
        ((PhantomJSDriver) ((WrapsDriver) driver).getWrappedDriver()).executePhantomJS(
                String.format("var page = this; page.uploadFile(arguments[0], '%s');", s.toString()), getElement());
    } else {
        getElement().sendKeys(keys);
    }
}



回答4:


var webPage = require('webpage');   
var page = webPage.create();
page.uploadFile('input[name=image]', '/path/to/some/photo.jpg');

in the new version of phantomjs, you can upload file like this uploadfile



来源:https://stackoverflow.com/questions/16323427/selenium-webdriver-java-upload-file-with-phantomjs-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!