如何在 Python 请求中使用代理
这是有关如何使用 Requests 在 Python 中设置和旋转代理的分步指南。
如何在 Python 请求中使用代理服务器
在开始之前,您需要满足以下先决条件:
- Python 3。 您需要安装最新的 Python 版本。
- 要求。 您可以通过运行来添加它
pip install requests.
- 代码编辑器。 使用您选择的任何编辑器。
如何使用请求设置代理:基本配置
步骤 1。 要使用 Python Requests 设置代理,请运行初始化命令。
import requests
步骤 2。 然后,添加一个包含代理信息的代理参数。
HTTP 代理:
proxies = {
'http': 'http://host:PORT',
'https': 'http://host:PORT',
}
SOCKS5代理:
proxies = {
'http': 'socks5://host:PORT',
'https': 'socks5://host:PORT',
}
步骤 3。 现在,让我们创建一个响应变量并传递代理参数。
response = requests.get('URL', proxies = proxies)
注意: 您可以使用任何请求方法,如 get()、post() 或 put()。
如何验证代理
要验证您的代理,请传递用户名和密码以及代理配置。
proxies = {
'http': 'http://user:password@host:PORT',
'https': 'http://user:password@host:PORT',
}
response = requests.get('URL', proxies = proxies)
如何设置代理会话
如果您想使用相同的代理配置发出多个请求,则需要创建一个会话并添加代理。您可以通过传递带有代理配置的会话对象并通过它发送请求来实现这一点。
session = requests.Session()
session.proxies = proxies
response = session.get('URL')
如何设置环境变量
如果您想要存储代理配置以供将来使用,则需要设置环境变量。这样,您可以轻松地在不同的代理设置之间切换,而无需修改代码。
步骤 1。 根据您的操作系统,您可以设置/导出环境变量到代理地址和端口。
对于Windows用户:
set http_proxy=http://username:password@:PORT
set https_proxy=http://username:password@:PORT
对于 Linux 用户:
export http_proxy=http://username:password@:PORT
export https_proxy=http://username:password@:PORT
步骤 2。 然后,导入 os 库并设置 代理 字典来使用环境变量。
import os
proxies = {
http: os.environ['http_proxy'],
https: os.environ['https_proxy']
}
requests.get('URL',proxies = proxies)
如何使用 Python 请求轮换代理
import requests
import random
步骤 2。 然后,定义您想要使用的 IP 地址列表。
proxy_pool = ['user:password@host:3001', 'user:password@host:3002', 'user:password@host:3003']
步骤 3。 现在,让我们看一下 10 个请求。
for i in range(10):
1)从您的池中选择一个随机代理。
proxy = {'http': random.choice(proxy_pool)}
2)使用相同的代理发送请求。
response = requests.get('URL', proxies=proxy)
3)打印响应。
print(response.text)
以下是完整脚本:
import requests
import random
# Define your proxies
proxy_pool = ['user:password@host:3001', 'user:password@host:3002', 'user:password@host:3003']
# Going through 10 requests
for i in range(10):
# Select a random proxy from the pool
proxy = {'http': random.choice(proxy_pool)}
# Send the request using the same proxy
response = requests.get('URL', proxies = proxy)
# Print the response
print(response.text)
亚当·杜波依斯
代理极客和开发人员。