AutoRedTools icon indicating copy to clipboard operation
AutoRedTools copied to clipboard

使用socks5作为代理时,会报错

Open vstVV opened this issue 1 year ago • 0 comments

报错信息如下: 检测到使用代理:socks5://*.*.*.*:port 配置错误,请检查无误后再重试!!! 报错位置应该是下面的函数:

    def __check_proxy__(self) -> bool:
        try:
            proxies = {"http": self.proxy,"https": self.proxy}
            requests.get("https://www.google.com",proxies=proxies)
        except Exception as e:
            error_msg = "检测到使用代理:%s 配置错误,请检查无误后再重试!!!" % (self.proxy)
            raise CustomException(error_msg)

问了GPT,回答是: _上述代码中的requests.get()方法默认使用的是HTTP代理,而不是SOCKS5代理。因此,如果你传入一个SOCKS5代理地址,这段代码将无法正确执行。

要在requests库中使用SOCKS5代理,你可以使用第三方库requests-socks来实现。下面是修改后的代码示例_:

import requests
from requests.exceptions import RequestException
from requests_sock import SocksiPyHandler

def __check_proxy__(self) -> bool:
    try:
        proxies = {
            'http': self.proxy,
            'https': self.proxy,
        }
        session = requests.Session()
        session.mount('http://', SocksiPyHandler(socks.SOCKS5, self.proxy))
        session.mount('https://', SocksiPyHandler(socks.SOCKS5, self.proxy))
        session.get("https://www.google.com", proxies=proxies)
    except RequestException as e:
        error_msg = "检测到使用代理:%s 配置错误,请检查无误后再重试!!!" % (self.proxy)
        raise CustomException(error_msg)
    return True

vstVV avatar Jun 14 '23 01:06 vstVV