Python Requests 用户代理指南:设置和更改

不要再被反机器人系统阻止!本教程将教您如何在 Python Requests 中设置和轮换 User-Agent 头,以实现安全且成功的网页抓取。
3 分钟阅读
Python Requests 用户代理指南:设置和更改

在本教程中,您将学习:

  • 为什么需要设置用户代理头
  • 默认的 Python requests 用户代理
  • 如何更改和取消在 Requests 中的用户代理
  • 如何在 Python 中实现用户代理轮换

让我们开始吧!

为什么您应该始终设置用户代理头

User-Agent HTTP 头由浏览器、执行网络请求的应用程序和 HTTP 客户端设置,用于识别发出请求的客户端软件。该值通常包括关于浏览器或应用程序类型、操作系统和请求来源架构的详细信息。

例如,截至目前,当 Chrome 访问网页时,所设置的用户代理如下:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36

该用户代理的组成部分包括:

  • Mozilla/5.0: 历史上用于表示与 Mozilla 浏览器的兼容性。现在通常作为用户代理的通用前缀出于兼容性原因添加。
  • Windows NT 10.0; Win64; x64: 操作系统 (Windows NT 10.0)、平台 (Win64) 和架构 (x64)。
  • AppleWebKit/537.36: 发出请求的 Chrome 版本使用的浏览器引擎。
  • KHTML, like Gecko: 与 KHTML 引擎和 Mozilla 使用的 Gecko 布局引擎兼容。
  1. Chrome/125.0.0.0: 浏览器名称及其版本。
  2. Safari/537.36: 与 Safari 兼容。

简而言之,用户代理对于识别请求是否来自知名浏览器或其他类型的软件至关重要。

爬虫机器人通常使用默认或不一致的用户代理字符串,暴露其自动化性质。因此,反爬虫解决方案通过查看 User-Agent 头来确定当前用户是否为合法用户或机器人,以保护网页上的数据。

有关更多详细信息,请阅读我们的 网页抓取的用户代理指南

默认的 Requests Python 用户代理是什么?

像大多数 HTTP 客户端一样,Requests 在发出 HTTP 请求时会设置 User-Agent 头。特别是,requests 设置的默认用户代理如下:

python-requests/X.Y.Z

其中 X.Y.Z 是您的项目中安装的 requests 包的版本。

通过向 httpbin.io/user-agent 端点发出 GET 请求来验证上面的字符串是否确实是 Requests 用户代理。此 API 返回从传入请求读取的 User-Agent 头。换句话说,它允许您检查 HTTP 客户端自动设置的用户代理。

导入 requests 并使用其 get() 方法执行所需的 HTTP 请求:

import requests

# make an HTTP GET request to the specified URL

response = requests.get('https://httpbin.io/user-agent')

# parse the API response as JSON and print it

print(response.json())

执行上述 Python 代码片段,您将得到类似于以下内容的输出:

{'user-agent': 'python-requests/2.32.3'}

用户代理为 python-requests/2.32.3,这清楚地表明请求来自 requests 库。因此,反机器人系统 可以将此类请求标记为非人类用户发出的,并立即将其阻止。这就是为什么更改 Python Requests 用户代理值如此重要的原因!

有关更多信息,请查看我们的 Python Requests 库完整指南

如何更改 Python Requests 用户代理

让我们看看如何在 Requests 中更改和取消 User-Agent 头的值!

设置自定义用户代理

Requests 不提供直接选项来设置用户代理值。同时,User-Agent 只是一个 HTTP 头。因此,您可以像其他 HTTP 头一样自定义其值,使用 headers 选项如下:

import requests

# custom user agent header

headers = {

  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'

}

# make an HTTP GET request to the specified URL

# setting custom headers

response = requests.get('https://httpbin.io/user-agent', headers=headers)

# parse the API response as JSON and print it

print(response.json())

再次执行上述 Python 代码片段,这次它将打印:

{'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'}

太棒了!您刚刚学会了设置自定义 Python requests 用户代理,您需要:

  1. 定义具有 user-agent 属性的Python 字典
  2. 将字典传递给您使用的 requests 方法的 headers 参数,以发出 HTTP 请求。

不要忘记 HTTP 头名称不区分大小写,因此头字典中的属性名称可以是您喜欢的格式。

注意:此方法也适用于 request()post()patch()put()delete()head()

要设置全局 requests 用户代理,您需要配置如下自定义 HTTP 会话:

import requests

# initialize an HTTP session

session = requests.Session()

# set a custom header in the session

session.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'

# perform a GET request within the HTTP session

response = session.get('https://httpbin.io/user-agent')

# print the data returned by the API

print(response.json())

# other requests with a custom user agent within the session ...

这将产生与之前相同的输出 。如果您不熟悉 Requests 中的 HTTP 会话,请查看文档

取消用户代理

发出 HTTP 请求而不设置用户代理是一个坏习惯,可能会轻易触发反机器人解决方案。然而,在某些情况下,您可能需要删除 User-Agent 头。

您可能首先想到的取消 Requests 中用户代理的方法是将 User-Agent 头设置为 None

import requests

# custom user agent header

headers = {

  'user-agent': None

}

# make an HTTP GET request to the specified URL

# setting custom headers

response = requests.get('https://httpbin.io/user-agent', headers=headers)

# parse the API response as JSON and print it

print(response.json())

这将不起作用,因为 requests 在后台使用 urllib3。因此,它将默认使用 urllib3 用户代理值:

python-urllib3/2.2.1

详细来说,/user-agent 端点将返回类似以下内容:

{'user-agent': 'python-urllib3/2.2.1'}

您需要做的是配置 urllib3 以跳过默认的用户代理值,使用 urllib3.util.SKIP_HEADER。通过定位 httpbin.io 的 /headers 端点来验证用户代理已被取消,该端点返回传入请求的 HTTP 头:

import requests

import urllib3

# exclude the default user agent value

headers = {

  'user-agent': urllib3.util.SKIP_HEADER

}

# prepare the HTTP request to make

req = requests.Request('GET', 'https://httpbin.io/headers')

prepared_request = req.prepare()

# set the custom headers with no user agent

prepared_request.headers = headers

# create a requests session and perform

# the request

session = requests.Session()

response = session.send(prepared_request)

# print the returned data

print(response.json())

运行上述 Python 代码,您将收到:

{'headers': {'Accept-Encoding': ['identity'], 'Host': ['httpbin.io']}}

惊人!如预期,无 Python requests 用户代理。

在 Requests 中实现用户代理轮换

将默认的 User-Agent 头更改为来自真实浏览器的适当值可能还不够。如果您使用相同的用户代理从相同的 IP 地址发出太多请求,可能会引起反机器人技术的怀疑。这些系统监控所有传入请求,知道自动化请求通常遵循规律的模式。

避免机器人检测的关键是随机化您的请求。让每个请求不同的好方法是用户代理轮换。这种技术的想法是不断更改 HTTP 客户端使用的用户代理头。这样,您可以使自动化请求看起来像是来自不同的浏览器,减少触发阻止或临时禁令的风险。

现在,按照以下步骤在 Requests 中实现用户代理轮换!

步骤#1:检索有效用户代理列表

从类似 User Agent String.com 的网站收集适当的用户代理列表,并将其存储在 Python 数组中:

user_agents = [

    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",

    "Mozilla/5.0 (Macintosh; Intel Mac OS X 14.5; rv:126.0) Gecko/20100101 Firefox/126.0",

    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:126.0) Gecko/20100101 Firefox/126.0"

    # other user agents...

]

步骤#2:提取随机用户代理

使用 random.choice() 从数组中随机提取用户代理字符串:

random_user_agent = random.choice(user_agents)

不要忘记上述行需要以下导入:

import random

步骤#3:设置随机用户代理并发出 HTTP 请求

定义具有随机用户代理的头字典并在 requests 请求中使用它:

headers = {

  'user-agent': random_user_agent

}

response = requests.get('https://httpbin.io/user-agent', headers=headers)

print(response.json())

这些指令需要此导入:

import requests

步骤#4:将所有内容组合在一起

您的 Python Requests 用户代理轮换逻辑将如下所示:

import random

import requests

# list of user agents

user_agents = [

    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",

    "Mozilla/5.0 (Macintosh; Intel Mac OS X 14.5; rv:126.0) Gecko/20100101 Firefox/126.0",

    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:126.0) Gecko/20100101 Firefox/126.0"

    # other user agents...

]

# pick a random user agent from the list

random_user_agent = random.choice(user_agents)

# set the random user agent

headers = {

  'user-agent': random_user_agent

}

# perform a GET request to the specified URL

# and print the response data

response = requests.get('https://httpbin.io/user-agent', headers=headers)

print(response.json())

多次执行此脚本,您将获得不同的用户代理字符串。

如此,您现在已经掌握了设置 Requests Python 用户代理值的技巧。

结论

在本指南中,您了解了设置 User-Agent 头的重要性以及如何在 requests 中进行设置。这样,您可以使基本的反机器人系统认为您的请求来自合法的浏览器。然而,先进的解决方案仍然可能检测并阻止您。为了防止 IP 禁止,您可以requests 中使用代理,但即便如此也可能不够!

通过 Web Scraper API 避免这些复杂情况。这一代的抓取 API 提供了一切您需要的功能,使用 requests 或任何其他 HTTP 客户端执行自动化网络请求。它依靠 IP 和用户代理轮换等功能轻松绕过反机器人技术。使成功的自动化请求变得前所未有的简单!

与我们的数据专家之一讨论我们的抓取解决方案,或通过注册立即探索所有可用产品。免费试用可用!

支持支付宝等多种支付方式

Antonello Zanini

技术写作

5.5 years experience

Antonello是一名软件工程师,但他更喜欢称自己为技术传教士。通过写作传播知识是他的使命。

Expertise
Web 开发 网页抓取 AI 集成