我正在尝试使用python发出HTTP请求。我尝试更改我的Windows系统代理(使用inetcpl.cpl
)
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(最近一次调用最后一次):文件“”,第1行,in response = urllib2.urlopen(request)文件“C:\ Python27 \ lib \ urllib2.py”,第126行,在urlopen中 return _opener.open(url,data,timeout)文件“C:\ Python27 \ lib \ urllib2.py”,第400行,打开 response = self._open(req,data)文件“C:\ Python27 \ lib \ urllib2.py”,第423行,在_open中 'unknown_open',req)文件“C:\ Python27 \ lib \ urllib2.py”,第378行,在_call_chain中 result = func(* args)文件“C:\ Python27 \ lib \ urllib2.py”,第1240行,在unknown_open中 提升URLError('未知网址类型:%s'%类型)URLError:
答案 0 :(得分:13)
我是OP。根据Tisho给出的答案,这对我有用:
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()
答案 1 :(得分:4)
似乎URLLIB2不支持SOCKS作为代理类型(如下所述:How can I use a SOCKS 4/5 proxy with urllib2?)。请查看http://code.google.com/p/socksipy-branch/以获取urllib + socks的示例。