1. 设置User-Agent

User-Agent是一个浏览器或其他客户端发送到服务器的标识,它告诉服务器有关客户端的信息,例如浏览器类型、操作系统、设备类型等。在使用Python进行HTTP请求时,可以设置User-Agent来模拟不同的客户端。

示例代码:

import requests

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

response = requests.get('http://httpbin.org/user-agent', headers=headers)
print(response.text)
  1. 设置Referer

Referer是HTTP请求头中的一个字段,它指定了请求的来源URL。在某些情况下,服务器会根据Referer来判断是否允许访问某些资源。在Python中,可以设置Referer来模拟请求来源。

示例代码:

import requests

headers = {
    'Referer': 'http://www.baidu.com',
}

response = requests.get('http://httpbin.org/headers', headers=headers)
print(response.text)
  1. 设置Cookie

Cookie是网站为了识别用户身份而存储在客户端浏览器中的一小段数据。在Python中,可以设置Cookie来模拟登录状态或其他用户身份信息。

示例代码:

import requests

cookies = {
    'name': 'value',
}

response = requests.get('http://httpbin.org/cookies', cookies=cookies)
print(response.text)
  1. 设置Authorization

Authorization是HTTP请求头中的一个字段,它指定了客户端的身份认证信息。在Python中,可以设置Authorization来模拟身份认证。

示例代码:

import requests

headers = {
    'Authorization': 'Bearer ACCESS_TOKEN',
}

response = requests.get('http://httpbin.org/headers', headers=headers)
print(response.text)
  1. 设置其他自定义头部

除了上述常用的HTTP头部字段外,还可以设置其他自定义头部字段,例如X-Requested-With、Accept-Encoding等。

示例代码:

import requests

headers = {
    'X-Requested-With': 'XMLHttpRequest',
    'Accept-Encoding': 'gzip, deflate, br',
}

response = requests.get('http://httpbin.org/headers', headers=headers)
print(response.text)
python get请求header常用设置

原文地址: https://www.cveoy.top/t/topic/qx7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录