关于python:如何使用Socksipy迭代代理列表

How can I iterate through a list of proxies with Socksipy

出于某种原因,我可以让这个工作,使用单一代理一切似乎都很好。
<代码>

1
2
3
4
5
6
#This works
import socks
import urllib2
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '68.xx.193.xx', 666)
socks.wrapmodule(urllib2)
print urllib2.urlopen('http://automation.whatismyip.com/n09230945.asp').read()

&安培;
<代码>

1
2
3
4
5
6
7
8
9
#This doesn't
import socks
import urllib2
proxies=['68.xx.193.xx','xx.178.xx.70','98.xx.84.xx','83.xx.86.xx']
ports=[666,1080,859,910]
for i in range(len(proxies)):
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, repr(proxies[i]), ports[i])
    socks.wrapmodule(urllib2)
    print urllib2.urlopen('http://automation.whatismyip.com/n09230945.asp').read()

错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Traceback (most recent call last):
  File"/home/zer0/Aptana Studio 3 Workspace/sy/src/test.py", line 38, in <module>
    print urllib2.urlopen('http://automation.whatismyip.com/n09230945.asp').read()
  File"/usr/lib/python2.7/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File"/usr/lib/python2.7/urllib2.py", line 391, in open
    response = self._open(req, data)
  File"/usr/lib/python2.7/urllib2.py", line 409, in _open
    '_open', req)
  File"/usr/lib/python2.7/urllib2.py", line 369, in _call_chain
    result = func(*args)
  File"/usr/lib/python2.7/urllib2.py", line 1185, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File"/usr/lib/python2.7/urllib2.py", line 1160, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno -5] No address associated with hostname>


运行这个:

1
2
3
4
proxies=['68.xx.193.xx','xx.178.xx.70','98.xx.84.xx','83.xx.86.xx']
ports=[666,1080,859,910]
for i in range(len(proxies)):
    print (repr(proxies[i]), ports[i])

你会得到

1
2
3
4
("'68.xx.193.xx'", 666)
("'xx.178.xx.70'", 1080)
("'98.xx.84.xx'", 859)
("'83.xx.86.xx'", 910)

您正在使用repr调用添加不需要的引号,因此urllib2认为它是主机名而不是IP地址。 摆脱它,你应该没事。