从 URL 下载文件并将其保存在 Python 文件夹中

Cha*_*lha 4 python python-requests

我有很多的URL与文件类型.docx.pdf我想运行一个python脚本从URL下载它们,并存储在文件夹中。这是我为单个文件所做的工作,我会将它们添加到 for 循环中:

response = requests.get('http://wbesite.com/Motivation-Letter.docx')
with open("my_file.docx", 'wb') as f:
    f.write(response.content)
Run Code Online (Sandbox Code Playgroud)

my_file.docx它保存的只有 266 字节并且已损坏,但 URL 很好。

更新:

添加了此代码并且它可以工作,但我想将它保存在一个新文件夹中。

import os
import shutil
import requests

def download_file(url, folder_name):
    local_filename = url.split('/')[-1]
    path = os.path.join("/{}/{}".format(folder_name, local_filename))
    with requests.get(url, stream=True) as r:
        with open(path, 'wb') as f:
            shutil.copyfileobj(r.raw, f)

    return local_filename
Run Code Online (Sandbox Code Playgroud)

Iva*_*dov 23

尝试使用选项:

import os
import requests


def download(url: str, dest_folder: str):
    if not os.path.exists(dest_folder):
        os.makedirs(dest_folder)  # create folder if it does not exist

    filename = url.split('/')[-1].replace(" ", "_")  # be careful with file names
    file_path = os.path.join(dest_folder, filename)

    r = requests.get(url, stream=True)
    if r.ok:
        print("saving to", os.path.abspath(file_path))
        with open(file_path, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024 * 8):
                if chunk:
                    f.write(chunk)
                    f.flush()
                    os.fsync(f.fileno())
    else:  # HTTP status code 4XX/5XX
        print("Download failed: status code {}\n{}".format(r.status_code, r.text))


download("http://website.com/Motivation-Letter.docx", dest_folder="mydir")
Run Code Online (Sandbox Code Playgroud)

请注意,mydir在上面的示例中是当前工作目录中的文件夹名称。如果mydir不存在脚本将在当前工作目录中创建它并将文件保存在其中。您的用户必须有权在当前工作目录中创建目录和文件。

您可以在 中传递绝对文件路径dest_folder,但请先检查权限。

PS:避免在一篇文章中提出多个问题


nci*_*ica 5

尝试:

import urllib.request 
urllib.request.urlretrieve(url, filename)
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是 urlretrieve 是 Python 2 的遗留函数,可能会在某个时候被弃用。到目前为止还没有,但文档警告说可能会这样。 (7认同)
  • 我想知道为什么这种常用且有用的方法在没有合适的替代品的情况下就被弃用了。 (5认同)