使用Python';s请求

使用Python';s请求,python,https,http-headers,python-requests,Python,Https,Http Headers,Python Requests,我正在编写一个小片段来从网页获取数据,目前我正在使用HTTP/HTTPS代理。请求的创建方式如下: headers = {'Proxy-Connection': 'Keep-Alive', 'Connection':None, 'User-Agent':'curl/1.2.3', } r = requests.get("https://www.google.es", headers=headers, proxies=proxyDict) 起初,HTTP

我正在编写一个小片段来从网页获取数据,目前我正在使用HTTP/HTTPS代理。请求的创建方式如下:

headers = {'Proxy-Connection': 'Keep-Alive',
       'Connection':None,
       'User-Agent':'curl/1.2.3',
       }
r = requests.get("https://www.google.es", headers=headers, proxies=proxyDict)
起初,HTTP和HTTPS都不起作用,代理在请求后返回403。同样奇怪的是,我可以使用
curl
进行HTTP/HTTPS请求,使用
apt-get
获取软件包,或者浏览网页。查看Wireshark后,我注意到
curl
请求与请求之间存在一些差异。将
User Agent
设置为伪
curl
版本后,代理立即允许我执行HTTP请求,因此我假设代理通过
User Agent
过滤请求

所以,现在我知道了我的代码失败的原因,我可以执行HTTP请求,但使用HTTPS代码仍然失败。我使用与HTTP相同的方式设置头,但是查看Wireshark后,CONNECT消息中没有发送头,因此代理不会看到任何
用户代理
,并返回拒绝访问的响应


我想,如果我能用CONNECT消息发送头,我就可以轻松地处理HTTPS请求,但我正在绞尽脑汁研究如何告诉请求我要发送头。

好的,所以我在查看http.client之后找到了一种方法。这比使用请求的级别要低一些,但至少可以工作

def HTTPSProxyRequest(method, host, url, proxy, header=None, proxy_headers=None, port=443):
    https = http.client.HTTPSConnection(proxy[0], proxy[1])
    https.set_tunnel(host, port, headers=proxy_headers)
    https.connect()
    https.request(method, url, headers=header)
    response = https.getresponse()
    return response.read(), response.status

# calling the function
HTTPSProxyRequest('GET','google.com', '/index.html', ('myproxy.com',8080))