【问题标题】:Can't send requests through socks5 proxy with Python无法使用 Python 通过 socks5 代理发送请求
【发布时间】:2021-11-08 02:48:09
【问题描述】:

我试图通过代理 (socks5) 发送 http/https 请求,但我不知道问题出在我的代码中还是代理中。

我尝试使用this code,但它给了我一个错误:

requests.exceptions.ConnectionError: SOCKSHTTPSConnectionPool(host='www.google.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x000001B656AC9608>: Failed to establish a new connection: Connection closed unexpectedly'))

这是我的代码:

import requests

url = "https://www.google.com"


proxies = {
    "http":"socks5://fsagsa:sacesf241_country-darwedafs_session-421dsafsa@x.xxx.xxx.xx:31112",
    "https":"socks5://fsagsa:sacesf241_country-darwedafs_session-421dsafsa@x.xxx.xxx.xx:31112",
    }

headers = {
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "Sec-Gpc": "1",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-User": "?1",
        "Accept-Encoding": "gzip, deflate, br",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Dest": "document",
        "Accept-Language": "en-GB,en;q=0.9"
    }


r = requests.get(url, headers = headers, proxies = proxies)

print(r)

然后,我使用online tool 检查了代理 该工具设法通过代理发送请求。 .

所以问题出在这段代码中?我不知道出了什么问题。

编辑 (15/09/2021)

我添加了标题,但问题仍然存在。

【问题讨论】:

  • 您是否尝试过添加标题来告诉您的网站您想要什么? :accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9accept-encoding: gzip, deflate, braccept-language: en-GB,en;q=0.9
  • 是的,我试过了。不幸的是,它并没有解决我的问题。

标签: python proxy python-requests socks


【解决方案1】:

除了基本的 HTTP 代理之外,Requests 还支持使用 SOCKS 协议的代理。这是一项可选功能,需要在使用前安装额外的第三方库。

您可以从 pip 获取此功能的依赖项:

$ python -m pip install requests[socks]

一旦您安装了这些依赖项,使用 SOCKS 代理就像使用 HTTP 代理一样简单:

proxies = {
            'http': 'socks5://user:pass@host:port',
            'https': 'socks5://user:pass@host:port'
          }

使用方案 socks5 会导致 DNS 解析发生在客户端,而不是代理服务器上。这与 curl 一致,它使用该方案来决定是在客户端还是代理上进行 DNS 解析。如果要解析代理服务器上的域,请使用 socks5h 作为方案。

【讨论】:

    【解决方案2】:

    使用 pytest 或其他带有 responses 库的测试框架创建本地服务器/模拟来处理请求,以消除应用程序/脚本外部的变量。我很确定 Google 会拒绝带有空标题的请求。此外,确保您安装了正确的依赖项以在请求中启用 SOCKS 代理支持 (python -m pip install requests[socks])。此外,如果您正在发出远程请求以连接到您的代理,则必须将 proxies 字典中的 socks5 更改为 socks5h

    参考文献

    pytest:https://docs.pytest.org/en/6.2.x/

    回复:https://github.com/getsentry/responses

    请求[socks]:https://docs.python-requests.org/en/master/user/advanced/#socks

    【讨论】:

    • 我已经尝试向该请求添加标头,并且我已经尝试了您提到的所有步骤。
    猜你喜欢
    • 1970-01-01
    • 2020-10-23
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多