如何通过socks代理使python请求工作

如何通过socks代理使python请求工作,python,proxy,socks,python-requests,Python,Proxy,Socks,Python Requests,我在Python脚本中使用了这个伟大的库: import requests r = requests.get("some-site.com") print r.text 我想使用socks代理。但是现在请求只支持HTTP代理 我该怎么做呢?现代方式: pip install -U requests[socks] 然后 您需要安装,我的版本是1.0,代码适用于我: import socket import socks import requests ip='localhost' # chang

我在Python脚本中使用了这个伟大的库:

import requests
r = requests.get("some-site.com")
print r.text
我想使用socks代理。但是现在请求只支持HTTP代理

我该怎么做呢?

现代方式:

pip install -U requests[socks]
然后

您需要安装,我的版本是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)

我在urllib3中安装了pysocks和猴子补丁的create_连接,如下所示:

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

一旦python
请求
SOCKS5
pull请求合并,它将像使用
代理
字典一样简单:

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

如果您无法等待
请求
准备就绪,则由于缺少
pwd
内置模块而无法使用
requesocks
,如GoogleAppEngine上所述,另一个选项是使用上述选项:

  • 从repo中抓取
    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()
    

    自2016年4月29日发布的
    请求
    版本起,
    请求
    支持SOCKS

    它需要,可与
    pip install pysocks
    一起安装

    用法示例:

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

    如果有人尝试了所有这些旧答案,但仍遇到以下问题:

    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.exceptions.ConnectionError:
    SOCKSHTTPConnectionPool(host='myhost',port=80):
    url:/my/path超过最大重试次数
    (由NewConnectionError(')引起:
    无法建立新连接:
    [Errno 8]提供了nodename或servname,或未知',))
    
    这可能是因为默认情况下,
    请求
    配置为在连接的本地端解析DNS查询

    尝试将代理URL从
    socks5://proxyhost:1234
    更改为
    socks5h://proxyhost:1234
    。注意额外的
    h
    (它代表主机名解析)


    ,我不知道为什么请求之间会出现这种模糊的分歧,但现在我们来了。

    我可以在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)'
    
    $pip3安装--用户“请求[socks]”
    $https_proxy=socks5://:python3-c\
    >"进口要求,;打印(请求。获取)https://httpbin.org/ip”。文本)
    
    您可以使用
    https\u proxy
    环境变量运行脚本

  • 如有必要,安装支架
  • 设置环境变量


  • 请注意,当使用SOCKS代理时,requesocks将发出带有完整URL的HTTP请求(例如,“GET HTTP/1.1”而不是“GET/HTTP/1.1”),此行为可能会导致问题。遗憾的是,目前似乎没有更好的解决方案。我使用的是zsh,我必须执行
    bash-c“pip安装-U请求[socks]”
    ,否则zsh会抱怨
    zsh:no-matches:requests[socks]
    。在Windows上,您还需要:pip安装win-inet-pton@BruceSun
    pip安装请求[socks]“
    就足够了,我需要在socks URL:
    socks5h://localhost:8080中添加一个“h”,因为主机名在我这边无法解析。从中,似乎“h”告诉库,服务器将是解析主机名的服务器。在最新版本中,它是这样工作的吗?没有
    requesocks
    ?这是最新
    请求的
    代理
    字典
    拉取请求,此时尚未合并@看,太好了!当我想通过socks 5代理使用软件包(例如flickrapi)时,这很方便。使用socks代理不是一个好方法,因为它会更改默认套接字,并会犯一些错误,所以如果只是测试一下就可以了,但不是真的。
    pip install-U requests[socks]
    就是我的例子,pip install-U requests[socks]光靠自己是行不通的。pip安装pysocks是必须的。正如对此所做的修改一样,要强制手动将您的
    requests
    版本升级到支持SOCKS(>2.10.0)的版本,请运行pip:
    pip install requests==2.18.4
    (撰写本文时为2.18.4),但请检查:是否为最新版本(此页面的顶部标题应该会显示最新的稳定版本)。我在这一页上与@DenMark合作。我的工作笔记本电脑是Mac电脑,要求[socks]只是卑鄙地拒绝为我安装,不管我怎么尝试…pysocks神奇地修复了一切。在我的情况下,
    socks
    模块名称与
    qBittorrent
    冲突,我需要删除/移动
    ~/.local/share/data/qBittorrent/nova3/socks.py
    并删除
    socks.pyc
    ,以解决错误消息
    模块“socks”没有属性“create_connection”
    和“socks”中的“bad magic number”:
    这正是我的问题!谢谢!这正是我的问题。它没有通过代理进行DNS查询。我一添加h,一切都正常工作。谢谢,
    socks5h
    方法比猴子补丁解决方案我以前担心我必须做。非常好。我找不到代理上Python文档的
    socks5h://
    任何地方。一定是找错地方了。我一定很喜欢。@Ligemer有时候唯一正确的地方就是代码。(但看过代码后,更新StackOverflow,现在有两个正确的地方可以看:)
    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',))
    
    $ pip3 install --user 'requests[socks]'
    $ https_proxy=socks5://<hostname or ip>:<port> python3 -c \
    > 'import requests;print(requests.get("https://httpbin.org/ip").text)'
    
    pip install PySocks
    pip install pysocks5
    
    export https_proxy=socks5://<hostname or ip>:<port>
    
    echo Your real IP
    python -c 'import requests;print(requests.get("http://ipinfo.io/ip").text)'
    
    echo IP with socks-proxy
    python -c 'import requests;print(requests.get("https://ipinfo.io/ip").text)'