📅  最后修改于: 2023-12-03 14:49:29.842000             🧑  作者: Mango
在网络爬虫或者 Web 开发中,可能需要通过代理请求访问网络资源。本文将简要介绍 Python 中如何进行代理请求。
requests 库是 Python 中常用的 HTTP 请求库之一,可以方便地进行 GET、POST 等各种请求。requests 库的一个优点是支持代理请求。
import requests
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'https://10.10.1.10:1080',
}
response = requests.get('http://httpbin.org/ip', proxies=proxies)
print(response.text)
上述代码中,我们使用了代理 IP 10.10.1.10:3128
访问 http://httpbin.org/ip
这个网站,并打印了返回结果。
urllib 库是 Python 中内置的 HTTP 请求库,它提供了类似 requests 库的 api。与 requests 库不同的是,urllib 库的代理设置需要通过创建一个代理处理器来完成。
import urllib.request
proxy_handler = urllib.request.ProxyHandler({
'http': 'http://10.10.1.10:3128',
'https': 'https://10.10.1.10:1080',
})
opener = urllib.request.build_opener(proxy_handler)
urllib.request.install_opener(opener)
response = urllib.request.urlopen('http://httpbin.org/ip')
print(response.read().decode())
上述代码中,我们同样使用了代理 IP 10.10.1.10:3128
访问 http://httpbin.org/ip
这个网站,并打印了返回结果。需要注意的是,在使用 urllib 库时,需要将代理处理器添加到 opener 中,并使用 urllib.request.install_opener() 方法进行安装。
本文介绍了 Python 中使用 requests 库和 urllib 库进行代理请求的方法,两种方法的核心都是通过设置代理地址即可。需要注意的是,代理地址的格式为 http://ip:port
或者 https://ip:port
,其中 ip
为代理服务器的 IP 地址,port
为代理服务器的端口号。在使用代理时,也需要注意代理服务器的稳定性和安全性。