如何使Python请求通过SOCKS代理工作(How to make python Requests

2019-06-18 07:45发布

我使用的是伟大的请求库在我的Python脚本:

import requests
r = requests.get("some-site.com")
print r.text

我想用SOCKS代理。 但要求只支持HTTP代理了。

我怎样才能做到这一点?

Answer 1:

现代的方式:

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'))


Answer 2:

作为requests版本2.10.0 ,在2016年4月29日公布, requests支持SOCKS。

它需要PySocks ,可与安装pip install pysocks

实例:

import requests
proxies = {'http': "socks5://myproxy:9191"}
requests.get('http://example.org', proxies=proxies)


Answer 3:

如果有人已经尝试了所有这些旧的答案,并仍在运行到类似的问题:

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:1234socks5h://proxyhost:1234 。 注意额外的h (它代表的主机名解析)。

该PySocks封装模块默认是做远程故障解决 ,我不知道为什么要求做他们融入这个费解的分歧,但我们在这里。



Answer 4:

你需要安装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)


Answer 5:

只要蟒蛇requests将被合并SOCKS5拉请求时,它还会像使用简单proxies词典:

#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 -就像GoogleAppEngine由于缺乏pwd内置模块,就是用PySocks是上面所提到的:

  1. 抓住socks.py从回购文件,并把副本在你的根文件夹;
  2. 加入import socksimport 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()


Answer 6:

# 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"
}


Answer 7:

我安装pysocks和urllib3猴子修补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


Answer 8:

也许这可以帮助:

https://github.com/kennethreitz/requests/pull/478



文章来源: How to make python Requests work via socks proxy