Python Selenium with Chrome,如何下载到指定文件名的指定文件夹

时间:2017-10-30 16:16:17

标签: python windows google-chrome selenium

该网站有一个下载按钮,我可以在python中

componentDidMount() {
  const { url, match } = this.props;
  if (url !== match.url) {
    fetchData(match.path);
  }
}

将文件下载到Chrome下载文件夹,其中包含网站指定的文件名。

有没有办法在Windows上更改目标文件夹和文件名?

4 个答案:

答案 0 :(得分:3)

您可以为chrome创建配置文件并定义测试的下载位置。这是一个例子:

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

options = webdriver.ChromeOptions() 
options.add_argument("download.default_directory=C:/Downloads")

driver = webdriver.Chrome(chrome_options=options)

答案 1 :(得分:2)

尝试:

    download_dir = "/yourDownloadPath/"
    chrome_options = webdriver.ChromeOptions()
    preferences = {"download.default_directory": download_dir ,
                   "directory_upgrade": True,
                   "safebrowsing.enabled": True }
    chrome_options.add_experimental_option("prefs", preferences)
    driver = webdriver.Chrome(chrome_options=chrome_options,executable_path=r'/pathTo/chromedriver')
    driver.get("urlfiletodownload");

答案 2 :(得分:0)

浪费了一段时间后,我发现推荐的解决方案对我没有有用:

options.add_argument("download.default_directory=C:/MyDownloadPath")

下面是对我有用的代码片段。 chromedriver.exe和我的python脚本位于同一文件夹中,我也想下载到同一文件夹中。如果chromedriver位于PATH中并且可以被硒找到,则不需要executable_path参数。

import os
from selenium import webdriver

localdir = os.path.dirname(os.path.realpath(__file__))
chromeOptions = webdriver.ChromeOptions()
prefs = { "download.default_directory" : localdir }
chromeOptions.add_experimental_option("prefs", prefs)
exe_path = os.path.join(localdir, 'chromedriver.exe')
with webdriver.Chrome(executable_path=exe_path, options=chromeOptions) as driver:
    # do your chrome download stuff here:
    driver.get(link)

我的系统:

Windows 10
Python 3.7.6
Chrome 80.0.3987.132
ChromeDriver 80.0.3987.106
Pip Module: Selenium 3.141.0
Date: March 2020

答案 3 :(得分:0)

工程!!!

将目录路径存储在变量中,并将变量传递到“ download.default_directory”

exepath = sys.arg[0]
# get the path from the .py file
Dir_path = os.path.dirname(os.path.abspath(exepath))
# get the path of "PDF_Folder" directory
Download_dir = Dir_path+"\\PDF_Folder\\"

preferences = {"download.default_directory": Download_dir , # pass the variable
                   "download.prompt_for_download": False,
                   "directory_upgrade": True,
                   "safebrowsing.enabled": True }
chrome_options.add_experimental_option("prefs", preferences)
driver = webdriver.Chrome(chrome_options=chrome_options,executable_path=r'/pathTo/chromedriver')
driver.get("urlfiletodownload");