用户名/密码代理无法正确运行python请求

时间:2019-09-20 21:17:11

标签: python proxy python-requests

我最近一直在尝试对Python请求使用代理,但似乎无法使它们正常工作。尽管请求与代理一起通过,但是我所做的测试使我相信代理并未应用到请求。即使存在明显不良的代理,我的请求仍会通过,这使我认为完全没有使用代理。为了演示这一点,我编写了一个简单的脚本(已经为该帖子编辑了工作代理):

import requests

proxy1 = {"http":"http://this:should@not:work"}
proxy2= {"http":"http://this:proxy@is.working.com:33128"}

r1 = requests.get("https://google.com", proxies=proxy2)
print(r1.status_code)
#prints 200 as expected
r2 = requests.get("https://google.com", proxies=proxy1)
print(r2.status_code)
#prints 200 which is weird since I was expecting the request to not go through

有人知道为什么会这样吗,以及请求实际上是否与代理一起使用?

1 个答案:

答案 0 :(得分:1)

在两个示例中,您仅定义http的代理

proxy1 = {"http": "http://this:should@not:work"}

proxy2 = {"http": "http://this:proxy@is.working.com:33128"}

但是您将网址与https:

一起使用
https://google.com

因此requests不使用代理。

您必须为https定义代理

proxy1 = {"https": "http://this:should@not:work"}

proxy2 = {"https": "http://this:proxy@is.working.com:33128"}

文档:requests: proxy


编辑:

使用https://httpbin.org/get,您可以测试GET请求,它会向您发送所有标头和IP

我从具有免费代理的页面中选择了一个代理,因此它可能在一段时间内无法工作

import requests

proxy = {"https": "104.244.75.26:8080"}

r = requests.get("https://httpbin.org/get", proxies=proxy1)
print(r.status_code)
print(r.text)

结果显示代理的IP

200
{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0"
  }, 
  "origin": "104.244.75.26, 104.244.75.26", 
  "url": "https://httpbin.org/get"
}