使用python从互联网下载文件? [英] Download a file from the internet in python?

查看:62
本文介绍了使用python从互联网下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 命名我下载的文件并为其分配文件类型时遇到问题.(请参见代码的第4行).
  • 将文件保存在任何位置,我专门为其分配了文件.与程序不在同一目录中.例如在下载,文档或任何目录中.
import requests
downloadUrl = input('Enter URL: ')
file_url = requests.get(downloadUrl)
dir_path = input("Enter path and name of the file: ")
f = open(dir_path,'a+')

有输入吗?

推荐答案

您正在打开一个请求对象,而不是文件路径

You are opening a requests object not a file path

file_url = requests.get(downloadUrl)
with open(file_url, 'w+') as f:

您需要在磁盘上的某个位置打开文件路径并对其进行写入

You would need to open a filepath on disk somewhere and write to that

请参见 https://stackabuse.com/download-files-上的使用请求模块with-python/

来自对帖子的评论

In [584]: link = "https://www.annualreports.com/HostedData/AnnualReportArchive/3/NASDAQ_QFIN_2018.pdf"

In [585]: import requests

In [586]: file_url = requests.get(link)

In [587]: with  open('/tmp/NASDAQ_QFIN_2018.pdf', 'wb') as f:
    ...:     f.write(file_url.content)
    ...:

In [588]: ls -al /tmp/NASDAQ_QFIN_2018.pdf
-rw-r--r--  1 ME  wheel  1796199  9 Apr 15:21 /tmp/NASDAQ_QFIN_2018.pdf

这篇关于使用python从互联网下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆