无法使用Python通过socks5代理发送请求

Clo*_*own 4 python proxy socks python-requests

我试图通过代理(socks5)发送http/https 请求,但我无法理解问题是否出在我的代码中或代理中。

我尝试使用这段代码,但它给了我一个错误:

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'))
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

然后,我用在线工具检查了代理 该工具设法通过代理发送请求。在线工具输出

那么问题出在这段代码中吗?我不明白出了什么问题。

编辑 (15/09/2021)

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

pyg*_*eek 6

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

\n

参考

\n

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

\n

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

\n

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

\n


小智 5

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

\n

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

\n
$ python -m pip install requests[socks]\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
proxies = {\n            'http': 'socks5://user:pass@host:port',\n            'https': 'socks5://user:pass@host:port'\n          }\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n