urllib中的response、error的使用介绍

  • 总结下昨天学习的代码知识,主要是python3的urllib的基础知识
  • 下面为urllib库中的response、error的使用介绍
  • import urllib.request
    from urllib import error
    #error 异常  error下有2个异常  except error.HTTPError as e 和 except error.URLError as e
    #分别为http错误  和  url错误
    
    #python3与python2区别
    # python2 如果代码有中文,需要在第一行加  #coding:utf-8
    # python2中  urllib2  ==  urllib.request    python3
    
    def download(url):
        response=urllib.request.urlopen(url,timeout=5)    #timeout  超时 5秒打不开就放弃了
        print(type(response))   #打印出 :  <class 'http.client.HTTPResponse'>
        #print(response.info())  #发送网络请求  详细的信息
        print(response.read(100))  #查看网页源代码 read()读取全部   read(100) 读取前面100个字符
    try:
        print(download("http://www.b.com"))
    except error.URLError as e:
        print("网络异常")

    以上代码运行结果如下:

  • 网络异常
    
    Process finished with exit code 0

     

posted on 2020-03-08 09:46  共感的艺术  阅读(882)  评论(0编辑  收藏  举报