如何使用python通过(tor)socks代理发出HTTP请求?

How to make HTTP request through a (tor) socks proxy using python?

我正在尝试使用python发出HTTP请求。 我尝试更改我的Windows系统代理(使用inetcpl.cpl)

1
2
3
4
5
6
url = 'http://www.whatismyip.com'
request = urllib2.Request(url)
request.add_header('Cache-Control','max-age=0')
request.set_proxy('127.0.0.1:9050', 'socks')
response = urllib2.urlopen(request)
response.read()

给了我错误

Traceback (most recent call last): File"", line 1, in

response = urllib2.urlopen(request) File"C:\Python27\lib\urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout) File"C:\Python27\lib\urllib2.py", line 400, in open
response = self._open(req, data) File"C:\Python27\lib\urllib2.py", line 423, in _open
'unknown_open', req) File"C:\Python27\lib\urllib2.py", line 378, in _call_chain
result = func(*args) File"C:\Python27\lib\urllib2.py", line 1240, in unknown_open
raise URLError('unknown url type: %s' % type) URLError:


我是OP。 根据Tisho给出的答案,这对我有用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import urllib, urllib2

##Download SocksiPy - A Python SOCKS client module. ( http://code.google.com/p/socksipy-branch/downloads/list )
##Simply copy the file"socks.py" to your Python's lib/site-packages directory, and initiate a socks socket like this.
## NOTE: you must use socks before urllib2.
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5,"127.0.0.1", 9050)
socket.socket = socks.socksocket

url = 'http://ifconfig.me/ip'
request = urllib2.Request(url)
request.add_header('Cache-Control','max-age=0')
response = urllib2.urlopen(request)
print response.read()


似乎URLLIB2不支持SOCKS作为代理类型(如下所述:如何使用带有urllib2的SOCKS 4/5代理?)。 有关urllib + socks的示例,请参阅http://code.google.com/p/socksipy-branch/。