zoukankan      html  css  js  c++  java
  • urllib基本使用-Handler和自定义的opener()

    """
    基本的urlopen()方法不支持代理、cookie等其他的HTTP/HTTPS高级功能。所以要支持这些功能:
    使用相关的 Handler处理器 来创建特定功能的处理器对象;
    然后通过 urllib.requestbuild_opener()方法使用这些处理器对象,创建自定义opener对象;
    使用自定义的opener对象,调用open()方法发送请求。
    如果程序里所有的请求都使用自定义的opener,
    可以使用urllib2.install_opener() 将自定义的 opener 对象 定义为 全局opener,
    表示如果之后凡是调用urlopen,都将使用这个opener(根据自己的需求来选择)
    """
    import urllib.request

    # 构建一个HTTPHandler 处理器对象,支持处理HTTP请求
    http_handler = urllib.request.HTTPHandler()

    # 构建一个HTTPHandler 处理器对象,支持处理HTTPS请求
    #http_handler = urllib.request.HTTPSHandler()

    # 构建一个HTTPHandler 处理器对象,支持处理HTTP请求,同时开启Debug Log,debuglevel 值默认 0
    http_handler = urllib.request.HTTPHandler(debuglevel=1)

    # 调用urllib.request.build_opener()方法,创建支持处理HTTP请求的opener 对象
    opener = urllib.request.build_opener(http_handler)

    # 构建Request请求
    request = urllib.request.Request('http://www.baidu.com/')

    # 调用自定义opener对象的open()方法,发送request请求
    response = opener.open(request)

    print(response.read().decode('utf-8'))
  • 相关阅读:
    maven编译时错误:无效的目标发行版
    参数传递方法(用Delphi的汇编代码解释)
    Playing with coroutines and Qt
    Qt的一些开发技巧
    刘晏:大唐经济战线的英雄
    Qt的焦点策略
    高级程序员与CTO技术总监首席架构师
    Python入门机器学习
    Service Mesh(服务网格)
    自定义博客园Markdown样式.超简单!
  • 原文地址:https://www.cnblogs.com/AndyChen2015/p/7418280.html
Copyright © 2011-2022 走看看