美文网首页
urllib、自定义opener

urllib、自定义opener

作者: zy小太阳 | 来源:发表于2018-12-23 16:28 被阅读0次

    urllib的parse模块主要是实现url的解析,合并,编码,解码

    from urllib import  parse
    
    #parse.urlparse实现了url的识别和分段
    url = 'https://www.1712B.com/daxuesheng?name=zhangsan#123'
    """
    url,:要解析和才分的url
    scheme='':设置协议,只有在url没有协议的情况下才会生效
    allow_fragments=True:是否忽略锚点,默认为True表示不忽略
    """
    result = parse.urlparse(url)
    """
    (scheme='https'(协议), netloc='www.1712B.com'(域), 
    path='/daxuesheng'(路径), params=''(可选参数), 
    query='name=zhangsan'(查询参数), fragment='123'(锚点))
    """
    print(result)
    #取出才分后的某一个参数
    print(result.scheme)
    
    #parse.urlunparse可以实现url的组合
    data = [sub_str for sub_str in result]
    print('-----',data)
    full_url = parse.urlunparse(data)
    print(full_url)
    
    #parse.uurlrljoin需要传递一个基类url,根据基类将某一个不完整的url拼接完整
    sub_url = '/p/123456'
    base_url = 'https://www.1712B.com/daxuesheng?name=zhangsan#123'
    full_url = parse.urljoin(base_url,sub_url)
    print('urljoin',full_url)
    
    #parse.urlencode将字典类型的参数,序列化为url的编码格式的字符串
    parmars = {
        'name':'张三',
        'class':'1712B',
    }
    result = parse.urlencode(parmars)
    print('urlencode',result)
    
    #parse.parse_qs反序列化,将url编码格式的字符串,转为字典类型
    result = parse.parse_qs(result)
    print('parse_qs',result)
    
    #parse.quote可以将中文字符,转为url编码格式
    kw = '摸摸摸'
    result = parse.quote(kw)
    print('quote',result)
    
    #将url编码进行解码
    result = parse.unquote(result)
    print('unquote',result)
    
    # 最最常用的是urljoin,urlencode两个方法
    

    urllib下使用代理

    # http/https代理
    # 一定是一个高匿代理理
    # 隐藏真实ip
    
    from urllib import request
    
    #自定义ProxyHandler的目的是为了设置代理,使用代理发起请求
    #proxies:对应的是一个字典
    # 代理有免费代理(西刺,快代理.....)
    # 和收费代理 (西刺,快代理.....,阿布云....)
    # proxies = {
    #     'http':'118.187.58.34:53281',
    #     'https':'124.235.180.121:80',
    # }
    
    #独享代理,需要账号密码做验证的
    proxies = {
        'http':'http://2295808193:6can7hyh@106.12.23.200:16818',
        'https':'https://2295808193:6can7hyh@106.12.23.200:16818'
    }
    handler = request.ProxyHandler(proxies=proxies)
    
    #自定义opener
    opener = request.build_opener(handler)
    
    #url地址
    #https://httpbin.org/get
    url = 'http://httpbin.org/get'
    
    response = opener.open(url)
    
    print(response.status)
    print(response.read().decode('utf-8'))
    

    urllib.error:在发起请求的过程中,可能会因为各种情况

    # 导致请求出现异常,因而导致代码崩溃,所以我们悬疑处理这些异常的请求
    
    from urllib import error,request
    
    # error.URLError
    
    def check_urlerror():
        """
        1.没有网络
        2.服务器连接失败
        3.找不到指定服务器
        :return:
        """
        url = 'http://www.baidu.com/'
        try:
            response = request.urlopen(url,timeout=0.01)
            print(response.status)
        except error.URLError as err:
            #[Errno -2] Name or service not known(未知服务器)
            #timed out:请求超时
            #[Errno -3] Temporary failure in name resolution(没网)
            print(err.reason)
    
    # check_urlerror()
    
    # error.HTTPError是URLError的子类
    
    def check_httperror():
        url = 'https://www.qidian.com/all/nsacnscn.htm'
        try:
            response = request.urlopen(url)
            print(response.status)
        except error.HTTPError as err:
            #HTTPError的三个属性
            #状态码
            print(err.code)
            #返回错误的原因
            print(err.reason)
            #返回响应头
            print(err.headers)
        except error.URLError as err:
            print(err.reason)
    
    check_httperror()
    

    自定义opener

    from urllib import request
    
    def send_request(req, timeout=100, context=None):
        """
        自己定义一个方法发起请求
        :param req: request请求对象
        :param timeout: 设置请求的超时时间
        :param context: 忽略ssl证书认证(ca证书)
        :return:
        handler:创建handler处理器是为了实现特定功能
        opener:为了使用opener.open方法发起请求
        """
        if context:
            handler = request.HTTPSHandler(context=context,debuglevel=1)
            opener = request.build_opener(handler)
            return opener.open(req, timeout=timeout)
        else:
            #debuglevel默认为0,设置为1的话表示开启debug模式,
            #会对请求进行跟踪,方便查看每一个请求的信息
            handler = request.HTTPSHandler(debuglevel=1)
            opener = request.build_opener(handler)
            return opener.open(req, timeout=timeout)
    
    url = 'http://www.baidu.com/'
    
    req_header = {
        'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
    }
    
    req = request.Request(url,headers=req_header)
    
    response = send_request(req)
    
    print(response.read().decode('utf-8'))
    

    相关文章

      网友评论

          本文标题:urllib、自定义opener

          本文链接:https://www.haomeiwen.com/subject/pyynkqtx.html