10

我正在尝试使用 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()

给了我错误

回溯(最后一次调用):文件“”,第 1 行,响应 = urllib2.urlopen(request) 文件“C:\Python27\lib\urllib2.py”,第 126 行,在 urlopen 返回 _opener.open(url,数据,超时)文件“C:\Python27\lib\urllib2.py”,第 400 行,打开响应 = self._open(req, data) 文件“C:\Python27\lib\urllib2.py”,第 423 行,在 _open 'unknown_open', req) 文件“C:\Python27\lib\urllib2.py”,第 378 行,在 _call_chain 结果 = func(*args) 文件“C:\Python27\lib\urllib2.py”,第 1240 行, 在 unknown_open raise URLError('unknown url type: %s' % type) URLError:

4

2 回答 2

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()
于 2012-06-10T11:06:35.793 回答
4

似乎 URLLIB2 不支持 SOCKS 作为代理类型(如此处所述:How can I use a SOCKS 4/5 proxy with urllib2?)。查看http://code.google.com/p/socksipy-branch/以获取 urllib+socks 的示例。

于 2012-06-10T09:43:46.267 回答