zoukankan      html  css  js  c++  java
  • 7-python自定义opener

    Handler处理器 和 自定义Opener

    • opener是 urllib2.OpenerDirector 的实例,我们之前一直都在使用的urlopen,它是一个特殊的opener(也就是模块帮我们构建好的)。

    • 但是基本的urlopen()方法不支持代理、cookie等其他的HTTP/HTTPS高级功能。所以要支持这些功能:

      1. 使用相关的 Handler处理器 来创建特定功能的处理器对象;
      2. 然后通过 urllib2.build_opener()方法使用这些处理器对象,创建自定义opener对象;
      3. 使用自定义的opener对象,调用open()方法发送请求。
    • 如果程序里所有的请求都使用自定义的opener,可以使用urllib2.install_opener() 将自定义的 opener 对象 定义为 全局opener,表示如果之后凡是调用urlopen,都将使用这个opener(根据自己的需求来选择)

    • py3是直接用urllib.request.HTTPHandler
    • #_*_ coding: utf-8 _*_
      
      '''
      Created on 2018年7月13日
      @author: sss
      功能:测试自定义http_handler
      
      '''
      
      import urllib.request
      
      #构建一个HttpHandler处理器对象,支持处理http请求
      # http_handler = urllib.request.HTTPHandler()
      http_handler = urllib.request.HTTPHandler(debuglevel = 1) #打开调试
      
      #构建一个HttpHandler处理器对象,支持处理https请求
      # http_handler = urllib.request.HTTPHandler()
      
      #调用创建支持处理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())
      

        

  • 相关阅读:
    CodeForces 383C-dfs序-线段树
    poj-3321-dfs序-线段树-邻接表
    poj2528-Mayor's posters-线段树离散化、基础
    hdu3333-Turing Tree-线段树+离线+离散化
    poj 1151-atlantis-线段树扫描线求面积并
    Changes favor the connective minds.
    HDU 4800/zoj 3735 Josephina and RPG 2013 长沙现场赛J题
    HDU 1203 I NEED A OFFER! 01背包
    hdu 1175 连连看 DFS
    Codeforces Round #208 (Div. 2) 358D Dima and Hares
  • 原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/9309316.html
Copyright © 2011-2022 走看看