我在Python脚本中使用了很棒的Requests库:
import requests
r = requests.get("some-site.com")
print r.text
我想用袜子代理。但是请求现在仅支持HTTP代理。
我怎样才能做到这一点?
Answers:
现代方式:
pip install -U requests[socks]
然后
import requests
resp = requests.get('http://go.to',
proxies=dict(http='socks5://user:pass@host:port',
https='socks5://user:pass@host:port'))
bash -c "pip install -U requests[socks]"
否则zsh会抱怨zsh: no matches found: requests[socks]
。
pip install 'requests[socks]'
就足够了
pip install -U requests[socks]
是enogh
requests
到支持SOCKS(> 2.10.0)的版本,请运行pip :(pip install requests==2.18.4
在撰写本文时为2.18.4),但请检查:pypi。 python.org/pypi/要求提供最新版本(此页面应在顶部标题中显示最新的稳定版本是什么)。
socks
与模块名称冲突qBittorrent
,我需要删除/移动~/.local/share/data/qBittorrent/nova3/socks.py
和删除socks.pyc
,解决错误信息module 'socks' has no attribute 'create_connection'
,并bad magic number in 'socks':
分别。
如果有人尝试了所有这些较早的答案,但仍然遇到诸如以下的问题:
requests.exceptions.ConnectionError:
SOCKSHTTPConnectionPool(host='myhost', port=80):
Max retries exceeded with url: /my/path
(Caused by NewConnectionError('<requests.packages.urllib3.contrib.socks.SOCKSConnection object at 0x106812bd0>:
Failed to establish a new connection:
[Errno 8] nodename nor servname provided, or not known',))
可能是由于默认情况下requests
配置为在连接的本地端解析DNS查询。
尝试将代理URL从更改socks5://proxyhost:1234
为socks5h://proxyhost:1234
。注意额外的内容h
(代表主机名解析)。
PySocks软件包模块的默认设置是进行远程解析,我不确定为什么请求使它们的集成变得如此模糊,但是我们到了。
socks5h
方法是这样比猴子修补解决方法我很担心我不得不做之前干净多了。
socks5h://
在代理服务器上找不到Python文档的任何地方。一定是在错误的地方找。爱得如此。
您需要安装pysocks,我的版本是1.0,该代码对我有用:
import socket
import socks
import requests
ip='localhost' # change your proxy's ip
port = 0000 # change your proxy's port
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, port)
socket.socket = socks.socksocket
url = u'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=inurl%E8%A2%8B'
print(requests.get(url).text)
一旦pythonrequests
将与SOCKS5
pull request合并,它将像使用proxies
dictionary一样简单:
#proxy
# SOCKS5 proxy for HTTP/HTTPS
proxies = {
'http' : "socks5://myproxy:9191",
'https' : "socks5://myproxy:9191"
}
#headers
headers = {
}
url='http://icanhazip.com/'
res = requests.get(url, headers=headers, proxies=proxies)
请参阅SOCKS代理支持
如果您无法等待request
准备就绪且无法使用时requesocks
(例如由于缺少pwd
内置模块而在GoogleAppEngine上),另一种选择是使用上面提到的PySocks:
socks.py
从仓库中获取文件,然后将副本放入根文件夹中;import socks
和import socket
在urllib2
下面的示例中,在与-一起使用之前,请配置并绑定套接字。
import urllib2
import socket
import socks
socks.set_default_proxy(socks.SOCKS5, "myprivateproxy.net",port=9050)
socket.socket = socks.socksocket
res=urllib2.urlopen(url).read()
# SOCKS5 proxy for HTTP/HTTPS
proxiesDict = {
'http' : "socks5://1.2.3.4:1080",
'https' : "socks5://1.2.3.4:1080"
}
# SOCKS4 proxy for HTTP/HTTPS
proxiesDict = {
'http' : "socks4://1.2.3.4:1080",
'https' : "socks4://1.2.3.4:1080"
}
# HTTP proxy for HTTP/HTTPS
proxiesDict = {
'http' : "1.2.3.4:1080",
'https' : "1.2.3.4:1080"
}
requesocks
?
我在urllib3中安装了pysocks和猴子补丁的create_connection,如下所示:
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "127.0.0.1", 1080)
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, socket_options=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default.
"""
host, port = address
if host.startswith('['):
host = host.strip('[]')
err = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socks.socksocket(af, socktype, proto)
# If provided, set socket level options before connecting.
# This is the only addition urllib3 makes to this function.
urllib3.util.connection._set_socket_options(sock, socket_options)
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except socket.error as e:
err = e
if sock is not None:
sock.close()
sock = None
if err is not None:
raise err
raise socket.error("getaddrinfo returns an empty list")
# monkeypatch
urllib3.util.connection.create_connection = create_connection
我可以在Linux上执行此操作。
$ pip3 install --user 'requests[socks]'
$ https_proxy=socks5://<hostname or ip>:<port> python3 -c \
> 'import requests;print(requests.get("https://httpbin.org/ip").text)'