Python请求不适用于https代理

2024-05-15 01:54:41 发布

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

我尝试在python中使用https代理,如下所示:

proxiesDict ={
  'http':  'http://' + proxy_line,
  'https': 'https://' + proxy_line
}


response = requests.get('https://api.ipify.org/?format=json', proxies=proxiesDict, allow_redirects=False)

proxy_line是从文件读取的代理,格式为ip:port。我在浏览器中检查了这个https代理,它工作正常。但在python中,这段代码会挂起几秒钟,然后就会出现异常:

^{pr2}$

我尝试使用socks5代理,它在安装了PySocks的socks5代理上工作。但是对于https我得到了这个例外,有人能帮我吗


Tags: httpsorgapijsonformathttp代理get
3条回答

尝试使用pycurl此函数可能有助于:

import pycurl

def pycurl_downloader(url, proxy_url, proxy_usr):
    """
    Download files with pycurl
    the proxy configuration:
    proxy_url = 'http://10.0.0.0:3128'
    proxy_usr = 'user:password'
    """

    c = pycurl.Curl()
    c.setopt(pycurl.FOLLOWLOCATION, 1)
    c.setopt(pycurl.MAXREDIRS, 5)
    c.setopt(pycurl.CONNECTTIMEOUT, 30)
    c.setopt(pycurl.AUTOREFERER, 1)

    if proxy_url: c.setopt(pycurl.PROXY, proxy_url)
    if proxy_usr: c.setopt(pycurl.PROXYUSERPWD, proxy_usr)

    content = StringIO()
    c.setopt(pycurl.URL, url)
    c.setopt(c.WRITEFUNCTION, content.write)

    try:
        c.perform()
        c.close()
    except pycurl.error, error:
        errno, errstr = error
        print 'An error occurred: ', errstr

    return content.getvalue()

requests指定代理列表时,密钥是协议,值是域/ip。您不需要再次指定http://https://作为实际值。在

因此,您的proxiesDict将是:

proxiesDict = {
  'http':  proxy_line,
  'https': proxy_line
}

也可以通过设置环境变量来配置代理:

$ export HTTP_PROXY="http://proxyIP:PORT"
$ export HTTPS_PROXY="http://proxyIP:PORT"

然后,只需执行python脚本而不需要代理请求。在

另外,您可以使用http://user:password@host配置代理

有关详细信息,请参阅此文档:http://docs.python-requests.org/en/master/user/advanced/

相关问题 更多 >

    热门问题