• python3网络爬虫系统学习:第二讲 基本库requests(一)


      之前,我们学习了基本库urllib的相关用法,但是在网页验证、Cookies处理等方面是比较繁琐的,需要用到Handler并且还需自己构建Opener。requests库的出现很好的解决了这个问题,下面让我们学习一下有关requests的操作。

      requests的安装可以直接使用pip install requests安装

      此处,小编建议重新安装pip,这样可以在任何目录使用pip,而不需要切换到pip所在目录下才可以使用,重装命令如下:

        python -m pip install --upgrade pip --force-reinstall

      接下来,进入正式学习

      一、基本用法

      1.GET请求

      GET请求的API如下:

    requests.get(url,params=None,**kwargs)

      参数详解:

      url:请求链接,必填项

      params:请求参数(requests接受的可选参数之一,在GET请求中较为常用)

      **kwargs:requests接受的可选参数,有params、data、json、headers、cookies、files、auth、timeout、allow_redirects、proxies、verify、stream以及cert。文章末尾小编总结了可选参数含义和用法。

      实例应用:

    import requests
    
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:66.0) Gecko/20100101 Firefox/66.0'}
    
    data = {
        'name': 'germey'
        'age': 22}
    
    # 读取网页
    url = 'http://httpbin.org/get'
    r = requests.get(url, params = params,headers = headers)
    print(r.text)
    
    # 读取图片/音频/视频等本质上是二进制的文件
    url = 'https://github.com/favicon.ico'
    r = requests.get(url, headers = headers)
    print(r.content)   #r.content返回bytes类型数据
    # 图片保存
    with open('f.ico', 'wb') as f:
        f.write(r.content)

      

      2.POST请求

      POST请求API如下:

    requests.post(url, data=None, json=None, **kwargs)

      参数详解:

      url:必填项,访问地址

      data:提交的表单数据,常用类型为dict或者str

      json:提交表单数据的另一种方式,常用类型为dict或者str

      **kwargs:requests接受的可选参数

      

      小编简单的说一下data参数和json参数的区别:

        1、不管jsonstr还是dict,如果不指定headers中的content-type,默认为application/json

        2、datadict时,如果不指定content-type,默认为application/x-www-form-urlencoded,相当于普通form表单提交的形式

        3、datastr时,如果不指定content-type,默认为application/json

        4、用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为'{"a": 1, "b": 2}'的这种形式

      常见的form表单可以直接使用data参数进行报文提交,而data的对象则是python中的字典类型;而在最新爬虫的过程中遇到了一种payload报文,是一种json格式的报文,因此传入的报文对象也应该是格式的。

      应用实例:

    import requests
    
    data = {
        'name': 'germey',
        'age': 22}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:66.0) Gecko/20100101 Firefox/66.0'}
    
    r = requests.post(url, headers=headers, data=data)
    print(r.text)

      3.响应

      在上面的实例中,通过使用text和content获取了响应内容。此外,还有很多方法和属性可以获得响应的其他信息。

        status_code——响应状态码

        headers——响应头

        cookies——响应Cookies

        url——响应网址

        history——请求历史

      4.requests内置状态码对象requests.codes

      例如,requests.codes.ok得到状态码200

      各状态码对应信息如下:

        # Informational.
        100: ('continue',),  
        101: ('switching_protocols',),  
        102: ('processing',),  
        103: ('checkpoint',),
        122: ('uri_too_long', 'request_uri_too_long'),
        200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\o/', ''),  
        201: ('created',),
        202: ('accepted',),
        203: ('non_authoritative_info', 'non_authoritative_information'),
        204: ('no_content',),
        205: ('reset_content', 'reset'),
        206: ('partial_content', 'partial'),
        207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
        208: ('already_reported',),
        226: ('im_used',),
    
        # Redirection.
        300: ('multiple_choices',),
        301: ('moved_permanently', 'moved', '\o-'),
        302: ('found',),
        303: ('see_other', 'other'),
        304: ('not_modified',),
        305: ('use_proxy',),
        306: ('switch_proxy',),
        307: ('temporary_redirect', 'temporary_moved', 'temporary'),
        308: ('permanent_redirect',
              'resume_incomplete', 'resume',),  # These 2 to be removed in 3.0
    
        # Client Error.
        400: ('bad_request', 'bad'),
        401: ('unauthorized',),
        402: ('payment_required', 'payment'),
        403: ('forbidden',),
        404: ('not_found', '-o-'),
        405: ('method_not_allowed', 'not_allowed'),
        406: ('not_acceptable',),
        407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
        408: ('request_timeout', 'timeout'),
        409: ('conflict',),
        410: ('gone',),
        411: ('length_required',),
        412: ('precondition_failed', 'precondition'),
        413: ('request_entity_too_large',),
        414: ('request_uri_too_large',),
        415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
        416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
        417: ('expectation_failed',),
        418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
        421: ('misdirected_request',),
        422: ('unprocessable_entity', 'unprocessable'),
        423: ('locked',),
        424: ('failed_dependency', 'dependency'),
        425: ('unordered_collection', 'unordered'),
        426: ('upgrade_required', 'upgrade'),
        428: ('precondition_required', 'precondition'),
        429: ('too_many_requests', 'too_many'),
        431: ('header_fields_too_large', 'fields_too_large'),
        444: ('no_response', 'none'),
        449: ('retry_with', 'retry'),
        450: ('blocked_by_windows_parental_controls', 'parental_controls'),
        451: ('unavailable_for_legal_reasons', 'legal_reasons'),
        499: ('client_closed_request',),
    
        # Server Error.
        500: ('internal_server_error', 'server_error', '/o\', ''),
        501: ('not_implemented',),
        502: ('bad_gateway',),
        503: ('service_unavailable', 'unavailable'),
        504: ('gateway_timeout',),
        505: ('http_version_not_supported', 'http_version'),
        506: ('variant_also_negotiates',),
        507: ('insufficient_storage',),
        509: ('bandwidth_limit_exceeded', 'bandwidth'),
        510: ('not_extended',),
        511: ('network_authentication_required', 'network_auth', 'network_authentication')

       常见错误代码以及错误原因如下:

      下面小编介绍一下这些可选参数分别是什么及其其用法:

      params:请求参数(在url中显现的),其值可以是字典、列表或者元组

      data:发送信息,主要用于POST请求中发送登录表单信息,其值通常为字典、列表或者元组,也可以是字节或者文件对象

      json:发送的JSON序列化数据,值当然为JSON格式

      headers:请求头,其值为字典数据

      cookies:值为字典或者CookieJar对象

      files:上传到服务器的文件。值为{'name': file-tuple}的字典以及('filename', fileobj)、('filename', fileobj, 'content_type')或('filename', fileobj, 'content_type', custom_headers)的元组数据。fileobj为文本读取数据,值为open(filename,mode)或者其他文本读取方式;content_type定义给定文件内容类型的字符串;custom_header是dict对象,包含要为文件添加的附加头。

      auth:授权元组

      timeout:超时设置,其值可以是数值对象也可以是二维元组对象

      allow_redirects:重定向设置,默认值为True

      proxies:代理设置,其值为{‘协议名’,url}格式的字典

      verify:证书认证,其值为bool型,默认为True

      stream:如果“False”,则立即下载响应内容。默认为True

      cert:添加证书文件,其值可以是String或者tuple。若为string,则为路径字符串;若为tuple,则为证书数据,构成样式为(cert,key)

      小编推一下自己新建的公众号,公众号内容更新快,每天定时更新,内容量适中,便于浏览和记忆

      

  • 相关阅读:
    keras多层感知机MLP
    局域网互通
    根号和分式
    vim简单的移动光标
    vim几种常用的插入模式
    LaTeX数学模式&上下标&代码块
    LaTeX入门
    ThinkPad X220i 安装 Mac OSX
    SUSE linux ,liveUSB制作方法
    KextWizard 的使用方法;以及Kext安装的几种工具下载
  • 原文地址:https://www.cnblogs.com/jpapplication/p/10752141.html
Copyright © 2020-2023  润新知