from pathlib import Path import shutil import textwrap from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait fixture_dir = Path("upload-fixture") fixture_dir.mkdir(exist_ok=True) sample_file = fixture_dir / "sample-upload.txt" sample_file.write_text("Selenium upload fixture\n", encoding="utf-8") html_file = fixture_dir / "upload.html" html_file.write_text( textwrap.dedent( """ Selenium upload fixture

""" ).strip(), encoding="utf-8", ) options = Options() options.add_argument("--headless=new") options.add_argument("--window-size=1280,720") for browser_name in ("google-chrome", "chromium", "chromium-browser"): browser_path = shutil.which(browser_name) if browser_path: options.binary_location = browser_path break driver_path = shutil.which("chromedriver") service = Service(driver_path) if driver_path else None driver = webdriver.Chrome(service=service, options=options) try: driver.get(html_file.resolve().as_uri()) file_input = driver.find_element(By.CSS_SELECTOR, "input[type='file']") file_input.send_keys(str(sample_file.resolve())) driver.find_element(By.ID, "submit").click() WebDriverWait(driver, 5).until( EC.text_to_be_present_in_element((By.ID, "result"), "uploaded: sample-upload.txt") ) selected_value = file_input.get_attribute("value") selected_name = selected_value.replace("\\", "/").split("/")[-1] result_text = driver.find_element(By.ID, "result").text print(f"selected: {selected_name}") print(f"result: {result_text}") finally: driver.quit()