urlopen函数

https://www.cnblogs.com/zyq-blog/p/5606760.html

一.  简介

    urllib.request.urlopen()函数用于实现对目标url的访问。

  函数原型如下:urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None) 

  函数定义如下:

复制代码
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
            *, cafile=None, capath=None, cadefault=False, context=None):
    global _opener
    if cafile or capath or cadefault:
        if context is not None:
            raise ValueError(
                "You can't pass both context and any of cafile, capath, and "
                "cadefault"
            )
        if not _have_ssl:
            raise ValueError('SSL support not available')
        context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
                                             cafile=cafile,
                                             capath=capath)
        https_handler = HTTPSHandler(context=context)
        opener = build_opener(https_handler)
    elif context:
        https_handler = HTTPSHandler(context=context)
        opener = build_opener(https_handler)
    elif _opener is None:
        _opener = opener = build_opener()
    else:
        opener = _opener
    return opener.open(url, data, timeout)
复制代码

二.  函数参数介绍

  <1>url 参数:目标资源在网络中的位置。可以是一个表示URL的字符串(如:http://www.xxxx.com/);也可以是一个urllib.request对象

  <2>data参数:data用来指明发往服务器请求中的额外的信息(如:在线翻译,在线答题等提交的内容)。HTTP是python中实现的众多网络通信http、https、ftp等协议中,唯一一个 使用data 参数的,也就是说只有打开的是http网址的时候,自定义data参数才会有作用。另外,官方API手册介绍指出:

               <2.1> data必须是一个字节数据对象(Python的bytes object)

     <2.2>data必须符合标准the standard application/x-www-form-urlencoded format,怎么得到这种标准结构的data呢?使用urllib.parse.urlencode()将自定义的data转换成

         标准格式,而这个函数所能接收的参数类型是pyhon中的mapping object(键/值对,如dict) or a sequence of two-element tuples(元素是tuple的列表)。

     <2.3>data也可以是一个可迭代的对象,这种情况下就需要配置response对象中的Conten-length,指明data的大小。

     <2.4>data默认是None,此时以GET方式发送请求;当用户给出data参数的时候,改为POST方式发送请求。

  <3>cafile、capath、cadefault 参数:用于实现可信任的CA证书的HTTP请求。(基本上很少用)

  <4>context参数:实现SSL加密传输。(基本上很少用)

三.  举个栗子

import urllib.request

url = 'http://www.baidu.com'
b = urllib.request.urlopen(url)

print (b.read())

结果:

如果不加read()最后会显示类对象:
 

参考:

  1. python3的urllib模块基本使用之urlopen-百度经验 
  2. Python爬虫之『urlopen』 - 做运维的小年轻 - 博客园 

 

原文地址:https://www.cnblogs.com/2016-11-13/p/13189565.html