Невозможно загрузить файл с помощью веб-драйвера Selenium

Я пытаюсь загрузить файл с помощью веб-драйвера selenium с помощью следующего кода:

        WebDriver driver = new HtmlUnitDriver();

        // And now use this to visit login page
        driver.get(URL_UPLOADFORM);

        // Find the text input element by its name
        WebElement userIDElement = driver.findElement(By.id("user_login"));
        userIDElement.sendKeys(USER_ID);

        WebElement passwordElement=driver.findElement(By.id("user_password"));
        passwordElement.sendKeys(PASSWORD);

        passwordElement.submit();
        // Enter something to search for
        //element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element and redirect to the form with file upload page
        //element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());
        System.out.println(driver.getCurrentUrl());


        WebElement fileUpload=driver.findElement(By.id("gallery_item_photo"));
        System.out.println(fileUpload.toString());
        fileUpload.sendKeys("C:\\Users\\abc\\Pictures\\fileimg.jpg");
        WebElement commitButton=driver.findElement(By.name("commit"));
        System.out.println(commitButton.toString());
        commitButton.click();

        System.out.println(driver.getCurrentUrl());
        driver.quit();

Файл не загружается, и вывод:

Page title is: New Photo
http://www.andromo.com/projects/276345/gallery_activities/24456/gallery_items/new
<input id="gallery_item_photo" name="gallery_item[photo]" value="" type="file" />
<button class="big button" name="commit" type="submit" value="commit">
http://www.andromo.com/projects/276345/gallery_activities/24456/gallery_items

Вот HTML-код элемента формы, с помощью которого я пытаюсь загрузить файл:

<form accept-charset="UTF-8" action="/projects/276345/gallery_activities/24456/gallery_items" class="formtastic gallery_item" enctype="multipart/form-data" id="new_gallery_item" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="A5lmLTkPubF7RXTrMN7+jNrHUsy0rsfHMW+Rpisjzug=" /></div>

    <fieldset class="inputs"><ol>

        <li class="string optional" id="gallery_item_title_input"><label for="gallery_item_title">Title</label><input id="gallery_item_title" maxlength="255" name="gallery_item[title]" type="text" />
<p class="inline-hints">What is this a photo of?</p></li>

        <li class="string optional" id="gallery_item_description_input"><label for="gallery_item_description">Description</label><input id="gallery_item_description" name="gallery_item[description]" type="text" />
<p class="inline-hints">Enter a short description of this photo</p></li>

        <li class="file optional" id="gallery_item_photo_input"><label for="gallery_item_photo">Upload Photo</label><input id="gallery_item_photo" name="gallery_item[photo]" type="file" />
<p class="inline-hints">Maximum 1024x1024, 2 MB, .JPG format</p></li>

        <li class="numeric required" id="gallery_item_position_input"><label for="gallery_item_position">Position<abbr title="required">*</abbr></label><input id="gallery_item_position" name="gallery_item[position]" type="text" value="100" />
<p class="inline-hints">Lower numbers appear first in your gallery</p></li>
</ol></fieldset>
    <fieldset class="buttons"><ol>
        <button class="big button" name="commit" type="submit" value="commit">Save Changes</button>
        <a href="/projects/276345/gallery_activities/24456/edit" class="big button">Cancel</a>
        <a href="http://support.andromo.com/kb/activities/photo-gallery-activity" class="big button" target="_blank">Help</a>
</ol></fieldset>   
</form>

Теперь интересно то, что если я заполняю вышеупомянутую форму в реальном браузере с загруженным файлом, то при отправке он выводит меня на URL: http://www.andromo.com/projects/276345/gallery_activities/24456/edit, Но с селеном это приводит меня к http://www.andromo.com/projects/276345/gallery_activities/24456/gallery_items ссылке, которая в реальном браузере (после входа в систему конечно) приводит меня к "извините это страница не существует ". и так, что здесь происходит? Я попытался сделать это и с HtmlUnit (см. Этот вопрос, который я опубликовал сегодня), но он дал мне тот же результат.

1 ответ

Решение

Ваш код выглядит правильно для меня. Я предполагаю, что файл существует в вашей системе. Вы также указываете абсолютный путь к файлу для загрузки, что также правильно. На мой взгляд, форма отправляется неправильно. Поэтому я бы рекомендовал использовать submit(); вместо click();

 WebElement commitButton=driver.findElement(By.name("commit"));
 commitButton.submit();

Из вашего комментария, похоже, submit(); работает на FirefoxDriver() и не для HtmlUnitDriver, Я заметил что твой HtmlUnitDriver не включен Javascript. Из документации здесь, попробуйте ниже

HtmlUnitDriver driver = new HtmlUnitDriver();
driver.setJavascriptEnabled(true);

или же

HtmlUnitDriver driver = new HtmlUnitDriver(true);

Также убедитесь, что у вас есть последняя библиотека Selenium.

Другие вопросы по тегам