zoukankan      html  css  js  c++  java
  • Python3爬虫一之(urllib库)

    urllib库是python3的内置HTTP请求库。

    ython2中urllib分为 urllib2、urllib两个库来发送请求,但是在python3中只有一个urllib库,方便了许多。

    urllib库官方文档地址:https://docs.python.org/3/library/urllib.html

    urllib库包含四个模块:

      request: 最基本的request请求模块,用来模拟的发送请求

      error: 异常处理模块用来捕获异常

      parse: 提供了许多URL处理方法,比如拆分、解析、合并

      robotparser: 用来识别网站的robot.txt文件

    发送请求:request下的urlopen()方法

    import urllib.request
    url = 'http://xa.meituan.com/meishi/'
    response = urllib.request.urlopen(url)
    print(response.read().decode())

    得到的response是一个HTTPResponse类型的对象,包含了 read(), readinto(), getheader(name), getheaders(), fileno()等方法和msg, version, status, debuglevel, closed等属性。

    使用urlopen()方法是也可以传递一些参数,如data, timeout 等

    data参数:

      data是可选参数,如果在请求中想要添加data参数, data参数必须用bytes()将其转化为bytes类型,并且,如果传递了参数,那么请求方式就是POST类型(urlopen请求方式默认是get)

    import urllib.request
    import urllib.parse
    data = bytes(urllib.parse.urlencode({'world':'Hello'}), encoding='utf-8')
    #传递一个data字典,使用bytes方法将data转为bytes类型,bytes方法的第一个参数是str,所以使用urllib.parse.urlencode()方法将字典转为str,第二个参数是编码格式
    url = 'http://xa.meituan.com/meishi/'
    response = urllib.request.urlopen(url=url, data=data)
    print(response.read().decode())

    timeout参数:

      该参数用于设定超时时间。单位是秒。超时就会抛出异常。

    import urllib.request
    url = 'http://xa.meituan.com/meishi/'
    response = urllib.request.urlopen(url=url, timeout=1)
    print(response.read().decode())

    其他参数: 

      context参数, 必须是ssl.SSLCentext类型, 用来指定SSL设置。

      cafile参数和capath参数分别指定CA证书与他的路径。

    request下的Request方法:

    Request的构造方法:

      urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)

    import urllib.request
    url = 'http://xa.meituan.com/meishi/'
    request = urllib.request.Request(url=url)
    response = urllib.request.urlopen(request)
    print(response.read().decode())

    origin_req_host: 请求方的host名称或者IP地址。

    unverifiable:表示这个请求是否是无法验证的,默认是False,意思是

    Handler

    urllib,request.BaseHandler类。他是所有Handler的父类。

    下面各种子类继承父类。

      HTTPDefaultErrorHandler: 用于处理HTTP请求

      HTTPRedirectHandler: 用于重定向。

      HTTP Cookie Processor:用于处理Cookies

      ProxyHandler:用于设置代理。

      HTTPPasswordMgr:用于管理密码。

      HTTPBasicAuthHandler: 用于认证管理。

    URL:  scheme + netloc + path +    parms + query + fragment

                协议         域名   访问路径   参数    查询条件     锚点

  • 相关阅读:
    IA__gdk_drawable_get_size: assertion 'GDK_IS_DRAWABLE (drawable)' failed
    宿主机系统 Deepin 15.4,解决 Virtualbox 5.1 中 XP虚拟机无法使用 USB设备(如:U盘、罗技优联接收器等)的问题
    Deepin安装Virtualbox扩展包出现与gksu-run-helper通信失败的解决
    docker 学习资料收集
    从编程语言的角度看中医的【藏像】理论
    从程序员视角和编程语言角度看【中医】:一种生命健康编程语言
    使用微服务架构思想,设计部署API代理网关和OAuth2.0授权认证框架
    在Office应用中打开WPF窗体并且让子窗体显示在Office应用上
    彻底关闭Excle进程的几个方法
    70后.net老猿,尚能饭否?
  • 原文地址:https://www.cnblogs.com/ss-py/p/9682621.html
Copyright © 2011-2022 走看看