通过 Tor 使用 python requests
问题:
你想使用 Tor 内置 SOCKS 代理通过 Tor 连接使用 python requests 库。
解决方案
首先确保 Tor 实际正在运行。我们将在此示例中使用端口 9050(默认)作为 SOCKS 端口。
不幸的是,requests 原生尚不支持 SOCKS 代理(详情请参见此问题)。因此你必须使用 requesocks,requests 的一个相当旧的分支。注意你可能无法使用最近添加的 requests 方法
通过运行 pip install requesocks 安装 requesocks。
这是一个返回你的 Tor 匿名化 IP 的简短示例:
requests_over_tor.py
#!/usr/bin/env python
#在 CC0 下发布
import requesocks
#初始化新的包装 requests 对象
session = requesocks.session()
#对 HTTP 和 HTTPS 都使用 Tor
session.proxies = {'http': 'socks5://localhost:9050', 'https': 'socks5://localhost:9050'}
#获取显示你 IP 地址的页面
response = session.get('http://httpbin.org/ip')
print(response.text)注意 requesocks 目前不适用于 Python3。作为替代,你可以使用 pycurl 如此处所述,或使用 SocksiPy 作为 urllib2 包装器如此处所述。
Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow