爬虫初学:01网络通信

from urllib import request  #网络通信模块

#相对路径:0312/01、网络通信.py
#绝对路径:D:\scoket原理\0312\01、网络通信.py
def downloader(url,isPicture=False):
    '''
   :param url :网址
   :param isPicture:默认是False值,表示为文本,如果下载的是图片,此值将赋值为True
   :return: none---直接报讯文件,不需要返回值
   '''
    #路径最后为文件名
    file_name=url.strip('/')[-1]


    #请求得到响应
    url='https://www.baidu.com/'
    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('index.html','w',encoding='utf-8') as fp:
            fp.write(content)

downloader('https://www.baidu.com/img/bd_logo1.png')

猜你喜欢

转载自blog.csdn.net/yuanzhen1/article/details/88427092