import urllib #网络通信模块 from urllib import request #请求得到相应 url="http://www.langlang2017.com/" response=urllib.request.urlopen(url) #查看请求响应 content=response.read() content=content.decode("utf-8") #对请求数据进行解码 #下载网页,写入自己的文件 with open("index.html","w",encoding="utf-8") as fb: fb.write(content) print(content)
import urllib #网络通信模块 from urllib import request def downloader(url,isPicture=False): #设置一个函数既可以下载文件也可以下载图片,图片是二进制保存的 """ :param url: 网址 :param isPicture: :return:None ,直接保存为文件,不需要返回值 """ file_name = url.split("/")[-1] #截取url最后一段为文件名 response=urllib.request.urlopen(url) #打开url路径,获取文件地址<http.client.HTTPResponse object at 0x0000000002E28A90> print(response) #查看请求相应 content=response.read() #把地址中的数据读取出来 if isPicture==True: #如果是图片的话就以如下方式复制到本机 with open(file_name,"wb") as fb: #图片以二进制写入 fb.write(content) # print(content) else: #如果是文件的话就以如下方式复制到本机 content = content.decode("utf-8") # 文件需要先对请求数据进行解码,然后再写入 with open("index1.html","w",encoding="utf-8") as fb: fb.write(content) # print(content) downloader("http://www.langlang2017.com/",isPicture=False) downloader("http://www.langlang2017.com/img/banner1.png",isPicture=True) HTTP:超文本传输协议(默认80端口)