40 lines
1.1 KiB
Python
40 lines
1.1 KiB
Python
from loguru import logger
|
||
import os
|
||
import urllib.request
|
||
|
||
|
||
def create_dir(path):
|
||
"""创建目录"""
|
||
if not os.path.exists(path):
|
||
os.mkdir(path)
|
||
logger.debug(f"成功创建目录: {path}")
|
||
logger.debug(f"目录地址已存在: {path}")
|
||
|
||
|
||
def download_attachment(url, path):
|
||
"""
|
||
通过Python自带的库urllib下载图片
|
||
需要导入:import urllib.request
|
||
:param url: url地址
|
||
:param path: 附件保存的绝对路径,需要带文件后缀
|
||
"""
|
||
try:
|
||
request = urllib.request.Request(url)
|
||
response = urllib.request.urlopen(request)
|
||
if response.getcode() == 200:
|
||
logger.debug("请求状态码200, 开始下载......")
|
||
with open(path, "wb") as fb:
|
||
fb.write(response.read())
|
||
return path
|
||
except Exception as e:
|
||
logger.debug("捕获到异常,下载失败")
|
||
return f"{e}"
|
||
|
||
|
||
if __name__ == '__main__':
|
||
import os
|
||
|
||
url = "https://www.gitlink.org.cn/api/attachments/416249"
|
||
path = os.path.join(r"C:\Users\chenyinhua\PycharmProjects\pythonProject7", "aaa.zip")
|
||
download_attachment(url, path)
|