文章目录
  1. 1. 前言
  2. 2. 使用
    1. 2.1. HTTP/HTTPS
    2. 2.2. SOCKS
    3. 2.3. Example
  3. 3. 参考资料
  4. 4. 文档信息

前言


由于某些原因(保护隐私),不希望对方看到自己的请求IP等信息,我们可以借助 IP 代理,让代理服务器作为中间人,从而保护我们的隐私。下面我们将以 Python 中 requests 网络库为中心展开。

使用


目前有两种主流的设置代理方法:一个是 http 协议,一个是 socks 协议。

HTTP/HTTPS


在代码中直接指定代理服务:

1
2
3
4
5
6
7
8
import requests

proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}

requests.get('http://example.org', proxies=proxies)

也可以通过 HTTP_PROXYHTTPS_PROXY 变量设置代理环境:

1
2
3
4
5
6
$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="http://10.10.1.10:1080"

$ python
>>> import requests
>>> requests.get('http://example.org')

如果代理服务器有 http 基本身份验证,可以使用http://user:password@host/ 语法,eg:

1
proxies = {'http': 'http://user:[email protected]:3128/'}

为特定的 schemehost 提供 代理,用 scheme://hostname 作为 key。这将匹配给定的 scheme 和 确定的hostname 的任意请求。

1
proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}

注意:代理中 URLs 必须包含 scheme.

SOCKS


安装 requests 依赖的 socks 特性:

1
2
3
pip install requests[socks]
or
pip install 'requests[socks]'

完成安装依赖后,socks 代理就像使用 http 代理一样:

1
2
3
4
5
6
7
8
9
proxies = {
'http': 'socks5://user:pass@host:port',
'https': 'socks5://user:pass@host:port'
}
eg:
proxies = {
"https": "socks5h://127.0.0.1:1081",
"http": "socks5h://127.0.0.1:1081",
}

注意:当 socks5 作为 scheme 时,DNS 解析发生在 客户端,并非在代理服务器。如果你想在代理服务器上进行解析,请用 socks5h 作为 scheme。

Example


仅供参考,在使用过程中,请结合自己需要进行更改。

1
2
3
4
5
6
7
8
9
10
11
import sys, os
import requests

proxy = {
"http": "http://221.229.252.98:9999",
"https": "https://221.229.252.98:9999",
}

ip_url = "http://api.getmyip.me/json"
resp = requests.get(ip_url, proxies=proxy)
print(resp.content)

在这里推荐一个获取公网IP的网址 https://api.getmyip.me ,能查看是否是透明代理还是匿名代理,同时支持 http 和 https 访问。

参考资料


文档信息


  • 版权声明:自由转载-保持署名-非商用-非衍生 ( CC BY-NC-ND 4.0 )
文章目录
  1. 1. 前言
  2. 2. 使用
    1. 2.1. HTTP/HTTPS
    2. 2.2. SOCKS
    3. 2.3. Example
  3. 3. 参考资料
  4. 4. 文档信息