Python的Requests库是一个功能强大的HTTP客户端库,它简化了发送HTTP请求和处理响应的过程。Requests库提供了简洁且易于使用的API,使得与HTTP资源的交互变得更加方便。本文将详细介绍如何使用Requests库进行GET和POST请求,设置headers、cookies、超时时间,以及如何处理代理和使用Session进行状态保持等高级功能。

安装Requests库

要使用Requests库,首先需要安装它。可以使用pip来安装最新版本的Requests:

bash
 pip install requests

或者,如果你使用的是Python 3:

bash
 pip3 install requests

安装完成后,就可以在Python代码中导入Requests库并使用它了。

发送GET请求

发送GET请求非常简单,只需要调用requests.get方法,并传入目标URL即可:

python
 import requests
 
  
 
 url = 'https://www.baidu.com'
 
 response = requests.get(url)
 
 print(response.text)

response.text会打印出响应的内容,它是将response.content(bytes类型)进行解码后的字符串。如果服务器没有指定编码方式,Requests会根据HTTP头部对响应的编码进行猜测,默认编码是"ISO-8859-1"。如果猜测错误,可能会导致解码产生乱码。此时,可以使用response.content.decode()并指定正确的编码方式来解决中文乱码问题。

发送POST请求

发送POST请求也很简单,只需要调用requests.post方法,并传入要发送的数据即可:

python
 import requests
 
  
 
 url = 'http://127.0.0.1:8080/login'
 
 headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"}
 
 data = {"username": "admin", "password": "123456"}
 
 response = requests.post(url, headers=headers, data=data)
 
 html = response.content.decode("utf-8")
 
 print(html)

在这段代码中,我们定义了一个URL、请求头和POST请求的参数,然后使用requests.post方法发送请求,并打印出响应的HTML内容。

设置Headers请求头

可以使用headers参数来设置请求头。headers参数接收一个字典形式的请求头,请求头字段名作为key,字段对应的值作为value。例如:

python
 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/110.0.0.0 Safari/537.36"}
 
 response = requests.get(url, headers=headers)
 
 print(response.content.decode())

处理Cookies

如果在一个响应中包含了cookie,那么可以利用cookies属性拿到这个返回的cookie值:

python
 import requests
 
  
 
 url = 'http://www.renren.com/PLogin.do'
 
 data = {"email": "970138074@qq.com", 'password': "pythonspider"}
 
 response = requests.get(url)
 
 print(response.cookies)
 
 print(response.cookies.get_dict())

使用Session进行状态保持

如果需要在多个请求之间共享cookie,可以使用Requests库提供的Session对象。Session对象能够保持跨请求的状态,包括cookies、HTTP头部信息等:

python
 import requests
 
  
 
 session = requests.Session()
 
  
 
 # 发送登录请求
 
 url = 'http://www.example.com/login'
 
 data = {"username": "user", "password": "pass"}
 
 session.post(url, data=data)
 
  
 
 # 发送另一个需要登录状态的请求
 
 another_url = 'http://www.example.com/protected'
 
 response = session.get(another_url)
 
 print(response.text)

设置超时时间

在发送请求时,可以设置超时时间。如果请求超过这个时间没有响应,则会抛出Timeout异常:

python
 import requests
 
  
 
 url = 'http://www.baidu.com'
 
 response = requests.get(url, timeout=5)  # 设置超时时间为5秒
 
 print(response.text)

使用代理

使用Requests添加代理也非常简单,只要在请求的方法中(比如get或者post)传递proxies参数即可:

python
 import requests
 
  
 
 url = 'http://httpbin.org/get'
 
 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'}
 
 proxy = {'http': '171.14.209.180:27829'}
 
 response = requests.get(url, headers=headers, proxies=proxy)
 
 with open('xx.html', 'w', encoding='utf-8') as fp:
 
     fp.write(response.text)

处理JSON数据

当服务器返回JSON格式的数据时,可以直接使用response.json()方法来解析它:

python
 import requests
 
  
 
 url = 'https://api.github.com/events'
 
 response = requests.get(url)
 
 events = response.json()
 
 print(events)

结论

Requests库是Python中一个非常强大且易于使用的HTTP客户端库。它简化了发送HTTP请求和处理响应的过程,提供了丰富的功能和选项。通过本文的介绍,希望读者能够掌握Requests库的基本用法和高级功能,并在实际开发中更加高效地处理HTTP请求。