zoukankan      html  css  js  c++  java
  • requsets模块的学习

    requests模块的学习

    使用之前
    • pip install requests
    发起get,post,请求获取响应
    • response = requests.get(url,headers) # 发起get请求,请求url地址对应的响应
    • response = requests.post(url,data={请求体的字典}) # 发起post请求

    response的用法

    • response.text
      • 该方式往往会出现乱码,出现乱码使用response.encoding="utf-8"
    • response.content.decode()
      • 把响应的二进制字节转化为str类型
      • bytes---> str
    • response.request.url # 发送请求的url地址
    • response.request.headers # 请求头
    • response.headers # 响应头
    获取网页的正确打开方式(通过下面三种获取解码之后的字符串)
    • 1、response.content.decode()
    • 2、response.content.decode("gbk")
    • 3、response.text
    发起带headers的请求
    • 为了模拟浏览器,获取和浏览器一样的内容
      headers = {
          "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
          "Referer": "http: // acc.hnczt.gov.cn / SpaceAction.do?method = list & ntype = 3",
          "Cookie": "Hm_lvt_35cde00bcde87c267839e0309e482db1 = 1554703285, 1554777297, 1554884326"
          }
      response = requests.get(url,headers)
      
    使用超时参数
    • pip install retrying
    from retrying import retry
    
    @retry(stop_max_attempt_number=3)
    # 数字3代表的是下面的函数执行三次,有一次成功则跳过,没有一次成功则跑出异常
    def func():
        print("this is func")
        raise ValueError("this is test error")
    
    处理cookie相关的请求
    • 直接携带cookie请求url地址

      • 1、cookie放在headers中
      headers = {
            "User-Agent":"...","Cookie":"cookie字符串"
      }
      
      • 2、cookie字典传递给cookies参数
        • requests.get(url, cookies=cookie_dict)
    • 先发送post请求,获取cookie,带上cookie请求登录的页面

      • 1、session = requests.session() # session具有的方法和requests一样
      • 2、session.post(url, data, headers) # 服务器设置在本地的cookie存在session
      • 3、session.get(url) # 会带上之前保存在session中的cookie, 能够请求成功
  • 相关阅读:
    第一次用NUnitAsp
    IT能够解决所有的商业问题吗?
    在这种东西里面,你会自在吗?
    看了段.net show之后的感想
    获取当前数据库中所有表的记录数
    对瀑布模型各阶段的解释
    Linux内核中的slab/slob/slub 在搞晕前先记下来
    分布式事务AT、TCC、Saga、XA 模式分析对比
    读懂Windows的“虚拟内存”为你量身定制
    示范NTFS 卷上的硬链接
  • 原文地址:https://www.cnblogs.com/liudemeng/p/10714844.html
Copyright © 2011-2022 走看看