文件上传

由于 Selenium 不能与文件上传对话框交互,因此它提供了一种无需打开对话框即可上传文件的方法。 如果该元素是一个类型为 fileinput 元素,则可以使用 send keys 方法发送将要上传文件的完整路径。

    WebElement fileInput = driver.findElement(By.cssSelector("input[type=file]"));
    fileInput.sendKeys(uploadFile.getAbsolutePath());
    driver.findElement(By.id("file-submit")).click();
Show full example
package dev.selenium.elements;

import dev.selenium.BaseChromeTest;
import java.io.File;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

public class FileUploadTest extends BaseChromeTest {

  @Test
  public void fileUploadTest() {
    driver.get("https://the-internet.herokuapp.com/upload");
    File uploadFile = new File("src/test/resources/selenium-snapshot.png");

    WebElement fileInput = driver.findElement(By.cssSelector("input[type=file]"));
    fileInput.sendKeys(uploadFile.getAbsolutePath());
    driver.findElement(By.id("file-submit")).click();

    WebElement fileName = driver.findElement(By.id("uploaded-files"));
    Assertions.assertEquals("selenium-snapshot.png", fileName.getText());
  }
}
    file_input = driver.find_element(By.CSS_SELECTOR, "input[type='file']")
    file_input.send_keys(upload_file)
    driver.find_element(By.ID, "file-submit").click()
Show full example
import os

from selenium import webdriver
from selenium.webdriver.common.by import By


def test_uploads(driver):
    driver.get("https://the-internet.herokuapp.com/upload")
    upload_file = os.path.abspath(
        os.path.join(os.path.dirname(__file__), "..", "selenium-snapshot.png"))

    file_input = driver.find_element(By.CSS_SELECTOR, "input[type='file']")
    file_input.send_keys(upload_file)
    driver.find_element(By.ID, "file-submit").click()

    file_name_element = driver.find_element(By.ID, "uploaded-files")
    file_name = file_name_element.text

    assert file_name == "selenium-snapshot.png"
            IWebElement fileInput = driver.FindElement(By.CssSelector("input[type=file]"));
            fileInput.SendKeys(uploadFile);
            driver.FindElement(By.Id("file-submit")).Click();
Show full example
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;

namespace SeleniumDocs.Elements
{
    [TestClass]
    public class FileUploadTest : BaseChromeTest
    {
        [TestMethod]
        public void Uploads()
        {
            driver.Url = "https://the-internet.herokuapp.com/upload";

            string baseDirectory = AppContext.BaseDirectory;
            string relativePath = "../../../TestSupport/selenium-snapshot.png";

            string uploadFile = Path.GetFullPath(Path.Combine(baseDirectory, relativePath));

            IWebElement fileInput = driver.FindElement(By.CssSelector("input[type=file]"));
            fileInput.SendKeys(uploadFile);
            driver.FindElement(By.Id("file-submit")).Click();

            IWebElement fileName = driver.FindElement(By.Id("uploaded-files"));
            Assert.AreEqual("selenium-snapshot.png", fileName.Text);
        }
    }
}
    file_input = driver.find_element(css: 'input[type=file]')
    file_input.send_keys(upload_file)
    driver.find_element(id: 'file-submit').click
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'File Upload' do
  let(:driver) { start_session }

  it 'uploads' do
    driver.get('https://the-internet.herokuapp.com/upload')
    upload_file = File.expand_path('../spec_support/selenium-snapshot.png', __dir__)

    file_input = driver.find_element(css: 'input[type=file]')
    file_input.send_keys(upload_file)
    driver.find_element(id: 'file-submit').click

    file_name = driver.find_element(id: 'uploaded-files')
    expect(file_name.text).to eq 'selenium-snapshot.png'
  end
end
    await driver.get('https://the-internet.herokuapp.com/upload');
    // Upload snapshot
Show full example

const {Browser, By, until, Builder} = require("selenium-webdriver");
const path = require("path");
const assert = require('node:assert');


describe('File Upload Test', function() {
  let driver;

  before(async function() {
    driver = new Builder()
      .forBrowser(Browser.CHROME)
      .build();
  });

  after(async() => await driver.quit());

  it('Should be able to upload a file successfully', async function() {
    const image = path.resolve('./test/resources/selenium-snapshot.png')

    await driver.manage().setTimeouts({implicit: 5000});

    // Navigate to URL
    await driver.get('https://the-internet.herokuapp.com/upload');
    // Upload snapshot
    await driver.findElement(By.id("file-upload")).sendKeys(image);
    await driver.findElement(By.id("file-submit")).submit();

    const revealed = await driver.findElement(By.id('uploaded-files'))
    await driver.wait(until.elementIsVisible(revealed), 2000);
    const data = await driver.findElement(By.css('h3'));

    assert.equal(await data.getText(), `File Uploaded!`);
  });
});

Move Code

```java import org.openqa.selenium.By import org.openqa.selenium.chrome.ChromeDriver fun main() { val driver = ChromeDriver() driver.get("https://the-internet.herokuapp.com/upload") driver.findElement(By.id("file-upload")).sendKeys("selenium-snapshot.jpg") driver.findElement(By.id("file-submit")).submit() if(driver.pageSource.contains("File Uploaded!")) { println("file uploaded") } else{ println("file not uploaded") } } ```