在headless firefox(Ubuntu)上使用selenium用python下载文件



我正试图找到一种方法,让这个脚本通过headless firefox下载文件。我没有看到它出现在我的下载目录中,也没有收到任何错误,有人能帮我找出如何下载这个文件吗?当没有在headless模式下完成时,此代码会正常工作。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
import requests
from selenium.webdriver.firefox.options import Options as FirefoxOptions

options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get('website')
sleep(2)
driver.maximize_window()
search = driver.find_element_by_id('UserName')
search.send_keys('username')
search = driver.find_element_by_id('Password')
search.send_keys('password')
search.send_keys(Keys.RETURN)
sleep(4)
driver.get('website')
sleep(8)
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "ej2-datetimepicker_0_input"))
)
element.click
link = driver.find_element_by_id('ej2-datetimepicker_0_input')
link.click()

except:
driver.quit()
driver.implicitly_wait(3)    
date = driver.find_element_by_xpath('//*[@id="ej2-datetimepicker_0_input"]')
date.clear()
date.send_keys('7/1/2020 - 8/24/2020')

sleep(3)
WebDriverWait(driver, 8).until(EC.element_to_be_clickable((By.XPATH, "//button[@mat-button]/span[@class='mat-button-wrapper']//span[text()='Excel']"))).click()
sleep(1)
print('done')

我也遇到了同样的问题。就我的情况而言,我正在下载PDF。你能试着禁用弹出下载对话框吗?以下内容对我有效。

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options

s = Service('./driver/geckodriver.exe')
download_dir = "download directory"
options = Options()
options.set_preference("pdfjs.disabled", True)
options.set_preference("browser.download.folderList", 2)
options.set_preference("browser.download.manager.useWindow", False)
options.set_preference("browser.download.dir", download_dir)
options.set_preference("browser.helperApps.neverAsk.saveToDisk", 
"application/pdf, application/force-download")
options.add_argument("--headless")
options.add_argument('--disable-gpu')
driver = webdriver.Firefox(service=s, options=options)

相关内容

  • 没有找到相关文章

最新更新