一、GET请求

1、当使用requests.get(url)方法发送GET请求时,它会向指定的URL发送一个HTTP GET请求,并返回一个包含服务器响应的Response对象。例如:

​url = "https://api.example.com/data"

response = requests.get(url)

2、添加URL参数:可以通过将参数作为字典传递给params参数来附加查询字符串参数。例如:

payload = {'key1': 'value1', 'key2': 'value2'}

response = requests.get(url, params=payload)

3、设置请求头:可以通过将请求头作为字典传递给headers参数来设置请求头。例如:

headers = {'User-Agent': 'Mozilla/5.0'}

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

4、设置超时时间:可以使用timeout参数设置请求的超时时间(以秒为单位)。例如:

response = requests.get(url, timeout=5)

5、获取响应对象:response变量将存储从服务器接收到的响应。可以使用该对象来获取有关响应的各种信息

  • 响应状态码:response.status_code属性返回服务器的响应状态码。例如:200表示成功,404表示页面未找到等。
  • 响应内容:response.text、response.content、response.json()都可以获取响应内容。
  • 敲黑板:这三者的区别!!!

  • response.text:返回响应的内容以字符串形式。例如,可以使用response.text来获取HTML页面的内容。
  • – 返回类型:字符串(Unicode 或者 str,根据返回内容自动推断)
  • – 适用场景:当处理文本类型的响应内容时(例如HTML页面、JSON数据等),通常使用`response.text`来获取内容。
  • – 文本编码:`requests`库会根据HTTP响应中的字符编码自动解码内容,并根据`Content-Type`头部指定的字符集来进行解码。你也可以手动设置`response.encoding`来覆盖自动检测到的编码。
  • response.content返回响应的内容以字符串(bytes)形式。例如,可以使用response.text来获取图片、音频、视频。
  • -返回类型:字节串(bytes)
  • -适用场景:当处理非文本类型的响应内容时(例如图片、音频、视频等二进制数据),通常使用response.content来获取内容。
  • -数据处理:获取的内容是未经处理的原始字节数据,适合于保存为文件或者传输给其他需要处理原始字节数据的模块
  • response.json():如果响应内容是JSON格式,可以使用response.json()方法将其解析为Python对象。
  • ​
    response = requests.get('https://api.example.com/data')
    
    data = response.json()
    
    # 处理JSON数据
    
    print(data['key'])
    
    ​
  • 响应头部:response.headers属性返回一个字典对象,包含服务器响应的所有头部信息。你可以使用response.headers['header_name']来获取特定头部的值。
  • 响应时间:response.elapsed属性返回一个timedelta对象,表示从发送请求到接收响应所花费的时间。
  • 响应URL:response.url属性返回最终响应的URL,经过重定向后可能与初始请求的URL不同。
  • 响应历史:response.history属性返回一个列表,包含所有重定向的Response对象。可以使用它来查看请求的重定向路径和每个重定向的状态码。
  • 错误处理:response.raise_for_status()方法可以在发生HTTP错误时引发异常(如404 Not Found或500 Internal Server Error)。你可以使用此方法来检查是否出现了错误,并根据需要进行处理。
  • 二、POST请求

    1、发送基本的POST请求:

    ​
    import requests
    
    url = "https://api.example.com/data"
    
    response = requests.post(url)
    
    ​

    2、发送表单数据

      import requests
    
       url = 'http://example.com/form'
       form_data = {
           'username': 'user1',
           'password': '123456'
       }
    
       response = requests.post(url, data=form_data)

    3、发送Json数据

    import requests
    import json
    
    url = 'http://example.com/api'
    data = {'key1': 'value1', 'key2': 'value2'}
    
    # 将参数编码为JSON格式
    json_data = json.dumps(data)
    
    # 设置请求头中的Content-Type为application/json
    headers = {'Content-Type': 'application/json'}
    # 发送POST请求
    response = requests.post(url, json=data)

    思考:可不可以用这两句发送请求?

    response = requests.post(url, data=json_data, headers=headers)

    response = requests.post(url, data=data, headers=headers)

    第一种:

    1. 使用json.dumps()转换数据并使用data参数:
    json_data = json.dumps(data)  
    response = requests.post(url, data=json_data, headers=headers)

    这是正确的方法。使用data=json_data时,实际上是在发送一个JSON格式的字符串,而不是Python字典。这要求API能够正确地解析这个字符串。在大多数情况下,服务器都能处理这种情况,但最后还是设置请求头:{'Content-Type': 'application/json'}  ,确保无误。

    第二种:

    1. 直接使用字典作为data参数:
    response = requests.post(url, data=data, headers=headers)

    这是错误的,因为默认情况下,data参数会将字典编码为application/x-www-form-urlencoded格式,而不是application/json

    最后:

    1. 使用json参数:
    response = requests.post(url, json=data)

    这是requests库推荐的方法来发送JSON数据,因为它会自动将数据编码为JSON,并设置正确的Content-Type头。不需要再手动设置Content-Type头,因为requests库会为您处理。

    所以这种方式最优。

    4、发送文件数据

     import requests
    
       url = 'http://example.com/upload'
       files = {'file': open('example.txt', 'rb')}
    
       response = requests.post(url, files=files)

    5、设置请求头

    url = "https://api.example.com/data"
    headers = {'User-Agent': 'Mozilla/5.0'}
    response = requests.post(url, headers=headers)

    6、设置超时时间

    url = "https://api.example.com/data"
    response = requests.post(url, timeout=5)

    7、获取响应对象:(和get方法一样。)

    
    url = "https://api.example.com/data"
    response = requests.post(url)
    #响应状态码
    print(response.status_code)
    #响应内容
    print(response.text)  # 返回类型:字符串
    print(response.content)  # 返回类型:字节串
    #响应头部
    print(response.headers['Content-Type'])
    #响应时间
    print(response.elapsed)
    #错误处理
    response.raise_for_status()

    8、发送原始数据:

    import requests
    
    url = 'http://example.com/api'
    data = 'Raw data'
    response = requests.post(url, data=data)

    9、发送XML数据:

    import requests
    
    url = 'http://example.com/api'
    data = '<xml><key1>value1</key1><key2>value2</key2></xml>'
    
    # 设置请求头中的Content-Type为application/xml
    headers = {'Content-Type': 'application/xml'}
    
    # 发送POST请求
    response = requests.post(url, data=data, headers=headers)

    作者:叶阿猪

    物联沃分享整理
    物联沃-IOTWORD物联网 » 【python】requests库学习

    发表回复