利用Python下载文件的方法有哪些

利用Python下载文件的方法有哪些?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

urllib.request

主要使用的是urlretrieve方法,该方法处理待淘汰的方法,不建议使用。

import urllib.request
 
url = 'https://cache..com/upload/information/20200622/113/21696.png'
urllib.request.urlretrieve(url, './image/logo.png')

requests

相比上述方案,可以返回HTTP的meta信息。

import requests
 
r = requests.get(url)
with open('./image/logo.png', 'wb') as f:
  f.write(r.content)
 
# Retrieve HTTP meta-data
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)

wget

wget是Linux下的一个命令行下载工具,在Python中可以直接通过安装包后使用。使用方法如下:

import wget
 
url = 'https://cache..com/upload/information/20200622/113/21696.png'
wget.download(url, './image/logo.png')

看完上述内容,你们掌握利用Python下载文件的方法有哪些的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!