Python利用requests模块实现代理访问网络

前言

代理相信很多人都听过,即使没有自己感受到,在无形之中可能也使用过,网络代理作为一项技术,在访问互联网时被广泛使用,那是因为使用代理有着诸多好处。

  • 使用代理IP能够突破自身的访问限制,不要把突破限制看成是坏事情,有时后恰恰是为了网络安全才使用了代理,比如内网的一台服务器只针对特定的IP提供访问权限,这时如果给内部人员分配指定的代理就可以进行访问,不比对所有的IP地址都开放,代理IP还可以进行自主管理。

  • 使用代理IP还提高访问速度,通常代理IP服务器都配置了一个较大的硬盘缓冲区,当缓冲区中保存有用户的请求信息时,则直接由缓冲区中取出信息,返回给用户,以提高访问速度。

测试环境

1
2
PS E:\> python --version
Python 3.6.7

代码实现

其实在Python 3中利用requests可以很方便的使用代理访问网络,比如下面这个简单的get方法:

1
requests.get(target_url, proxies=proxy_data)

其中需要注意的就是 proxies 参数的值,这里换成可以代理的ip就可以了,网上流传着众多的代理IP,只要可用就可以拿来代理IP访问,不过这些免费的IP失效性非常差,常常过几分钟就失效了,下面就给出一个完整的例子,检测代理IP是否可用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import requests

test_ip = '116.209.56.118'
test_port = '9999'

def test_proxy_request(ip, port):
# 代理IP地址
proxy_data = {
'http': 'http://' + ip + ':' + port,
'https': 'http://' + ip + ':' + port,
}

# 客户端说明
head_data = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
'Connection': 'keep-alive'
}

try:
# 该返回当前的IP地址,http://icanhazip.com提供返回当前外网IP的服务
response = requests.get('http://icanhazip.com', headers=head_data, proxies=proxy_data)
outer_ip = response.text.strip().replace('\n', '')
return outer_ip == ip
except:
return False

if __name__ == '__main__':
test_result = test_proxy_request(test_ip, test_port)
if test_result:
print("IP代理成功 ==> {0}:{1}".format(test_ip, test_port))
else:
print("IP代理失败 ==> {0}:{1}".format(test_ip, test_port))

需要注意,其中只有这一句requests.get('http://icanhazip.com', headers=head_data, proxies=proxy_data)是代理的重点。

测试结果

IP代理成功 ==> 116.209.56.118:9999

Albert Shi wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客