uploading files from headless

Viewed 49

I have such an element that allows me to upload a file by clicking:

<a class="gray_box" href="#">Choose world folder<span>Select the world folder, we'll do the rest</span></a>

The problem is that when clicked, it calls the file manager screenshot

first I did the download like this:

import pyautogui

button = wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[href='#']"))).click()

pyautogui.write(<path>)
pyautogui.press('enter')

but this does not allow me to upload the file in headless mode

because the path is inserted directly into the console and the "confirmation window" is called, which has to be confirmed manually

how do I make a file upload to work in headless mode?

3 Answers

Uploading files with Selenium is done by sending the uploaded file full path string to a special element. This element can be located with the following XPath "//input[@type='file']" or in CSS Selector style "input[type='file']".
So, if the file you wish to upload is for example "C:\my_folder\the_file.png" it can be uploaded with Selenium with the following code line:

driver.find_element(By.XPATH, "//input[@type='file']").send_keys("C:\my_folder\the_file.png")

Some websites request a user agent in headless mode, edit this argument in your work and try again.

chrome_options.add_argument("--user-agent=User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36")
import pyautogui
import time
from selenium.webdriver.common.keys import Keys
driver.get('https://chunker.app/#')

button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[href='#']"))).click()
time.sleep(2)
pyautogui.write(path+Keys.ENTER)
pyautogui.press('enter')
time.sleep(2)
pyautogui.press('enter')
time.sleep(2)
pyautogui.press('enter')

This currently goes through that in nonheadless so far haven't tested headless. It was about 4 enters in total.

Related