如何使用 Selenium ChromeDriver 和 Chrome 在自定义位置下载文件

How to download files in customized location using Selenium ChromeDriver and Chrome

我想将 txt 和 pdf 文件下载到特定文件夹。但它只是将它们下载到另一个文件夹中。网站 http://demo.automationtesting.in/FileDownload.html。是代码有问题还是我没有放正确的文件夹位置?

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chromeOptions=Options()
chromeOptions.add_experimental_option("prefs", {"download.default_dictionary": "C:\DownloadedAutomationFiles"})

driver=webdriver.Chrome(executable_path="D:\ChromeDriverExtracted\chromedriver", chrome_options=chromeOptions)
driver.get("http://demo.automationtesting.in/FileDownload.html")
driver.maximize_window()

driver.find_element_by_id("textbox").send_keys("testing")
driver.find_element_by_id("createTxt").click()   #generate file button
driver.find_element_by_id("link-to-download").click()    #dowload link


#Download PDF FILE

driver.find_element_by_id("pdfbox").send_keys("testing download text file")
driver.find_element_by_id("createPdf").click()   #generate file button
driver.find_element_by_id("pdf-link-to-download").click()    #dowload link

time.sleep(2)
driver.close()

要在 Automation Demo Site to a specific folder using , and 中下载所需文件,您需要通过 add_experimental_option()[= 传递首选项 "download.default_directory" 以及值(目录位置) 24=] 并且您可以使用以下解决方案:

代码块:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option("prefs", {
  "download.default_directory": r"C:\Data_Files\output_files"
  })
s = Service('C:\BrowserDrivers\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
driver.get("http://demo.automationtesting.in/FileDownload.html")
driver.execute_script("return arguments[0].scrollIntoView(true);", WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Download"))))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "textbox"))).send_keys("testing")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "createTxt"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "link-to-download"))).click()

快照: