且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Python 中使用两级代理设置?

更新时间:2022-06-22 00:45:50

Update 听起来您希望连接到代理 A,然后通过代理 B、C、D 启动 HTTP 连接,在 A 之外.您可能会查看 proxychains 项目,它说它可以通过用户隧道传输任何协议-定义的 TOR、SOCKS 4/5 和 HTTP 代理链".

Update Sounds like you're looking to connect to proxy A and from there initiate HTTP connections via proxies B, C, D which are outside of A. You might look into the proxychains project which says it can "tunnel any protocol via a user-defined chain of TOR, SOCKS 4/5, and HTTP proxies".

版本 3.1 在 Ubuntu Lucid 中作为一个包提供.如果它不能直接为您工作,proxychains 源代码 可能会提供有关如何为您的应用实施此功能的一些见解.

Version 3.1 is available as a package in Ubuntu Lucid. If it doesn't work directly for you, the proxychains source code may provide some insight into how this capability could be implemented for your app.

原始答案:查看 urllib2.ProxyHandler.以下是如何使用多种不同代理打开网址的示例:

Orig answer: Check out the urllib2.ProxyHandler. Here is an example of how you can use several different proxies to open urls:

import random
import urllib2

# put the urls for all of your proxies in a list
proxies = ['http://localhost:8080/']

# construct your list of url openers which each use a different proxy
openers = []
for proxy in proxies:
    opener = urllib2.build_opener(urllib2.ProxyHandler({'http': proxy}))
    openers.append(opener)

# select a url opener randomly, round-robin, or with some other scheme
opener = random.choice(openers)
req = urllib2.Request(url)
res = opener.open(req)