from urllib import request#网络通信模块
#相对路径:01.网络通信.py
#绝对路径:E:\0312\01.网络通信.py
def downloader(url,isPicture=False):
‘’’
:param url: 网址
:param isPicture: 默认是False值,表示是文本,如果下载的是图片,此值将赋值为True
:return: none—直接保存成文件,不需要返回值
‘’’
#路径最后为文件名
file_name = url.split(’/’)[-1]
#请求得到响应
response = request.urlopen(url)
#查看响应内容
content = response.read()
#图片和文本区别保存
if isPicture:
with open(file_name,'wb') as fp:
fp.write(content)
else:
content = content.decode('utf-8')
with open(file_name,'w',encoding='utf-8') as fp:
fp.write(content)
downloader('https://www.baidu.com/img/bd_logo1.png',isPicture=True)
本文介绍了一个使用Python进行网络通信并下载文件的简单方法。通过定义downloader函数,可以指定URL来下载文本或图片,并根据文件类型进行相应处理。对于图片,采用二进制方式保存;对于文本,则进行解码后保存。
1528

被折叠的 条评论
为什么被折叠?



