Requests库详解、详细使用、高级用法

Requests是一个优雅而简单的 Python HTTP 库

1.Requests库快速入门

1.1 Requests库安装

pip install requests

1.2 发送请求

        现在,让我们尝试获取一个网页,比如百度。

import  requests

url = 'https://www.baidu.com/'

response = requests.get(url=url)

print(response)

//'<Response [200]>'

        Requests库不仅仅能够发送get请求,post、put、delete、head、options等请求都能发送,仅仅需将get替换成相应的请求方式。

1.3 携参发送

        为了模拟正常的http请求,请求头、请求参数、请求体都是需要具体网页具体分析的。

接下来模拟百度的get请求。

import  requests

url = 'https://www.baidu.com/'

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'
}

response = requests.get(url=url,headers = headers)

print(response.text)

        response.text可以输出响应数据,可能是html页面也可能是字符串又或者是json数据。

        只有正确的模拟了请求头中的UA参数,get访问百度才会正确的返回完整的html页面。

        除去headers以外,requests请求还有许多可选参数params、data、json、cookies、files等。

2.requests库高级用法

2.1 会话对象

        Session 对象允许在请求之间保留某些参数,它还会在 Session 实例发出的所有请求中保留 cookie,并将使用urllib3连接池。

        Session 对象具有主 Requests API 的所有方法。

s = requests.Session()

s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('https://httpbin.org/cookies')

print(r.text)
//'{"cookies": {"sessioncookie": "123456789"}}'

        Session对象可以在发送请求之前设置默认数据。例如:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# 'x-test'和'x-test2'都将携带发送,以下称为方法级参数,以上称为会话级参数
s.get('https://httpbin.org/headers', headers={'x-test2': 'true'})

        但请注意,即使使用会话,方法级参数也不会在请求之间保留。方法级参数可以覆盖会话级参数,只要设置了会话级参数,发送方法级参数时,会话级参数也会一并发送。方法级参数只会在请求发送方法时生效,不会携带至下一次请求中,但会话级参数会在以后的请求中继续生效。例如:

s = requests.Session()
s.cookies.update({
    'user':'eriiat'
})

r = s.get('https://httpbin.org/cookies', cookies={'from-my': 'browser'})
print(r.text)
'''
{
  "cookies": {
    "from-my": "browser", 
    "user": "eriiat"
  }
}'''

r = s.get('https://httpbin.org/cookies')
print(r.text)
'''
{
  "cookies": {
    "user": "eriiat"
  }
}'''

相关推荐

  1. Requests详解详细使用高级

    2023-12-08 17:24:01       34 阅读
  2. 详解WebMvcConfigurer

    2023-12-08 17:24:01       26 阅读
  3. 【Python】requests的介绍及

    2023-12-08 17:24:01       26 阅读
  4. Windows Shell命令详解:掌握命令行的高级

    2023-12-08 17:24:01       20 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-08 17:24:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-08 17:24:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-08 17:24:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-08 17:24:01       18 阅读

热门阅读

  1. 折半查找(数据结构实训)

    2023-12-08 17:24:01       38 阅读
  2. 博客摘录「 C语言之二维数组赋值」

    2023-12-08 17:24:01       27 阅读
  3. kali常用命令

    2023-12-08 17:24:01       33 阅读
  4. springboot快速入门

    2023-12-08 17:24:01       36 阅读
  5. 虚拟化之Stage2地址翻译

    2023-12-08 17:24:01       34 阅读
  6. 对音频打上标签,从标签开始播放

    2023-12-08 17:24:01       36 阅读
  7. oceanBase存储返回多个值

    2023-12-08 17:24:01       36 阅读
  8. 【android开发-20】android中notification的用法讲解

    2023-12-08 17:24:01       29 阅读