zoukankan      html  css  js  c++  java
  • 数据获取--爬虫-3(Request库)

    Request库使用教程


    相比于urllib更加简便易用的HTTP库。

    Requests

    GET请求:只需要向requests.get()方法中传入相应的url即可以实现GET请求并获得Response。POST请求使用requests.post()方法实现代码如下:

    #GET请求
    import requests
    
    response = requests.get('https://www.baidu.com/')
    print(response)
    #POST请求
    import requests
    
    data = {'name': 'germey', 'age': '22'}
    response = requests.post("http://httpbin.org/post", data=data)
    print(response.text)
    

    requests库中提供更简便的传入参数的方法,将一个字典形式的参数传递给params参数就能直接实现在url中添加参数。POST请求的DataForm也可以直接这样设置具体代码如下:

    # GET请求
    import requests
    
    data = {
    	'name': 'germey',
    	'age': 22
    }
    response = requests.get("http://httpbin.org/get", params=data)
    print(response.text)
    
    # POST请求
    import requests
    
    data = {'name': 'germey', 'age': '22'}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
    }
    response = requests.post("http://httpbin.org/post", data=data, headers=headers)
    print(response.json())
    

    设置headers:直接将headers信息传入get()函数相应的参数中即可,POST请求headers设置方法相同(相应代码见上一个代码块)代码如下:

    import requests
    
    headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
    }
    response = requests.get("https://www.zhihu.com/explore", headers=headers)
    print(response.text)
    

    Response

    1. json解析:requests库提供了简单易用的json解析方式,如果Response返回为json格式,.json()方法能直接将Request保存成json格式,这与使用json.loads()函数效果完全一样。代码如下:

      import requests
      import json
      
      response = requests.get("http://httpbin.org/get")
      print(type(response.text))
      print(response.json())#使用json方法解析
      print(json.loads(response.text))#使用loads方法转化为json,与上一行比较返回结果一样。
      print(type(response.json()))
      
    2. 获取二进制数据:想要从网页获取图片和视频等数据需要使用.content方法,然后将使用文件保存操作将内容保存到本地。代码如下:

      import requests
      
      response = requests.get("https://github.com/favicon.ico")#通过传入URL下载图片
      print(type(response.text), type(response.content))
      print(response.text)
      print(response.content)#文件的二进制编码,与urllib库一样。
      
      with open('favicon.ico', 'wb') as f:#保存文件
          f.write(response.content)
          f.close()
      
    3. 状态码:使用.status_code()方法可以获得服务器返回的状态码,每一个状态码都对应一种状态,对应情况见下表:

      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'),
      

    可以通过这些状态码获取服务器状态:

    import requests
    
    response = requests.get('http://www.jianshu.com/hello.html')
    print(type(response.status_code), response.status_code)
    exit() if not response.status_code == requests.codes.not_found else print('404 Not Found')#方法一:使用状态码对应的信息进行验证。
    
    response = requests.get('http://www.jianshu.com')
    print(type(response.status_code), response.status_code)
    exit() if not response.status_code == 200 else print('Request Successfully')
    #使用状态码值进行验证
    #其实我不理解这两种方法的语法结构
    #我看了一下官方文档,如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),我们可以通过 Response.raise_for_status() 来抛出异常:
    
    import requests
    bad_r = requests.get('http://www.jianshu.com')
    print(bad_r.status_code)
    bad_r.raise_for_status()
    

    高级操作

    1. 文件上传

      import requests
      #用open方法打开图片,储存到file中,保存到字典files中。
      files = {'file': open('favicon.ico', 'rb')}
      #发送Request时将其传入对应的参数中
      response = requests.post("http://httpbin.org/post", files=files)
      print(response.text)#获取并打印结果
      
    2. cookies:requests库中提供了.cookies方法获取cookies,得到的cookies为json格式。

      import requests
      
      response = requests.get('http://www.jianshu.com')
      print(type(response.cookies), response.cookies)
      print(response.cookies)#可以直接导出cookie不需要先声明CookieJar类,更简单。
      for key, value in response.cookies.items():#打印json格式的cookies
          print(key + '=' + value)
      

      通过cookies可以实现模拟登陆, 需要注意的是,模拟对话必须在同一次调用进行 如果需要多次调用,requests中提供了Session类,实现在同一次对话中发起多次请求。

      import requests
      
      url = 'http://httpbin.org/cookies'
      cookies = dict(cookies_are='working')#设置cookies
      #一次请求并获取反馈
      r = requests.get(url, cookies=cookies)
      print(r.text)
      #多次请求
      s = requests.Session()
      s.get(url, cookies=cookies)
      response = s.get(url)
      print(response.text)
      
    3. 证书验证:在爬去HTTPS网站时,浏览器会首先检测证书是否合法,如果证书有问题会直接抛出SSLError,程序会终止。为了避免此类情况,可以选择不验证,不验证证书会发出警告,可以使用代码消除,代码如下:

      import requests
      #消除警告操作
      from requests.packages import urllib3
      urllib3.disable_warnings()
      #verify参数设置为False,不验证
      response = requests.get('https://www.12306.cn', verify=False)
      print(response.status_code)
      
    4. 代理设置:将代理信息保存在字典中,并传入相应参数中即可,代码如下:

      import requests
      #http代理
      proxies = {
          "http": "http://user:password@127.0.0.1:9743/",
      "https": "https://127.0.0.1:9743",
      }#如果代理有密码,可以在域名前进行设置,用冒号分割。
      proxies = {
          'http': 'socks5://127.0.0.1:9742',
          'https': 'socks5://127.0.0.1:9742'
      }#如果使用SSR代理,需要提前安装'requests[socks]',如上设置即可
      response = requests.get("https://www.taobao.com", proxies=proxies)
      print(response.status_code)
      
    5. 超时处理:为访问指定时间, 为了捕获Timeout异常,需要找到Timeout属于哪一个类。

      import requests
      from requests.exceptions import ReadTimeout
      try:
          response = requests.get("http://httpbin.org/get", timeout = 0.5)
          print(response.status_code)
      except ReadTimeout:#Timeout属于ReadTimeout异常类
          print('Timeout')
      
    6. 认证设置:有些网站 访问时 会就会有认证,不通过验证无法打开页面那种。在auth中传入元组类型用户名和密码即可。

      import requests
      
      r = requests.get('http://120.27.34.24:9001', auth=('user', '123'))
      print(r.status_code)
      
    7. 异常处理:实例:

      import requests
      from requests.exceptions import ReadTimeout, ConnectionError, RequestException
      try:
          response = requests.get("http://httpbin.org/get", timeout = 0.5)
          print(response.status_code)
      except ReadTimeout:
          print('Timeout')
      except ConnectionError:
          print('Connection error')
      except RequestException:
          print('Error')
      
    8. 其他功能:

      print(type(response.url), response.url)
      print(type(response.history), response.history)
      print(response.text)#与urllib库中的response.read()功能相同
      
      
  • 相关阅读:
    源码编译安装 screen
    关于精简安装office2010的步骤
    关于shell脚本时遇value too great for base (error token is "08")
    关于web服务器访问速度慢的一些简单解决方法
    vim 打开Linux下文件每一行后面都有^M的样式
    logrotate关于日志轮询和分割
    补实验四及第二章家庭作业
    第五周学习总结
    第四周学习总结
    第三周学习总结
  • 原文地址:https://www.cnblogs.com/lizhe-Ning/p/11710617.html
Copyright © 2011-2022 走看看