将代理设置为 urllib.request (Python3) [英] Setting proxy to urllib.request (Python3)

查看:114
本文介绍了将代理设置为 urllib.request (Python3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为 Python 3 中的最后一个 urllib 设置代理.我在做下一个

How can I set proxy for the last urllib in Python 3. I am doing the next

from urllib import request as urlrequest
ask = urlrequest.Request(url)     # note that here Request has R not r as prev versions
open = urlrequest.urlopen(req)
open.read()

我尝试添加代理如下:

ask=urlrequest.Request.set_proxy(ask,proxies,'http')

但是我不知道它有多正确,因为我收到了下一个错误:

However I don't know how correct it is since I am getting the next error:

336     def set_proxy(self, host, type):
--> 337         if self.type == 'https' and not self._tunnel_host:
    338             self._tunnel_host = self.host
    339         else:

AttributeError: 'NoneType' object has no attribute 'type'

推荐答案

您应该在 Request实例上调用 set_proxy()>,而不是课程本身:

You should be calling set_proxy() on an instance of class Request, not on the class itself:

from urllib import request as urlrequest

proxy_host = 'localhost:1234'    # host and port of your proxy
url = 'http://www.httpbin.org/ip'

req = urlrequest.Request(url)
req.set_proxy(proxy_host, 'http')

response = urlrequest.urlopen(req)
print(response.read().decode('utf8'))

这篇关于将代理设置为 urllib.request (Python3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆