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

2024-04-26 00:00:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python脚本中使用了很棒的Requests库:

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

我想用袜子代理。但是请求现在只支持HTTP代理。

我该怎么做?


Tags: textimport脚本comhttp代理getsite
3条回答

自2016-04-29发布的requests版本2.10.0起,requests支持SOCKS。

它需要PySocks,可以用pip install pysocks安装。

示例用法:

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

现代方式:

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

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

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(它代表主机名解析)。

The PySocks package module default is to do remote resolution,我也不知道为什么请求会有如此明显的分歧,但现在我们来了。

相关问题 更多 >

    热门问题