繁体   English   中英

将代理设置为 urllib.request (Python3)

[英]Setting proxy to urllib.request (Python3)

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

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')

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

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() ,而不是在类本身上调用:

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'))

我需要在我们公司的环境中禁用代理,因为我想访问本地主机上的服务器。 我无法使用@mhawke 的方法禁用代理服务器(尝试将{}None[]作为代理传递)。

这对我有用(也可用于设置特定代理,请参阅代码中的注释)。

import urllib.request as request

# disable proxy by passing an empty
proxy_handler = request.ProxyHandler({})
# alertnatively you could set a proxy for http with
# proxy_handler = request.ProxyHandler({'http': 'http://www.example.com:3128/'})

opener = request.build_opener(proxy_handler)

url = 'http://www.example.org'

# open the website with the opener
req = opener.open(url)
data = req.read().decode('utf8')
print(data)

Urllib 将自动检测在环境中设置的代理- 因此您可以在您的环境中设置HTTP_PROXY变量,例如用于 Bash:

export HTTP_PROXY=http://proxy_url:proxy_port

或使用 Python 例如

import os
os.environ['HTTP_PROXY'] = 'http://proxy_url:proxy_port'

来自 urllib 文档的注意事项:“如果设置了变量REQUEST_METHODHTTP_PROXY [环境变量] 将被忽略;请参阅有关getproxies () 的文档”

我通常将以下代码用于代理请求:

import requests
proxies = {
    'http': 'http://proxy.server:port',
    'https': 'http://proxyserver:port',
}
s = requests.Session()
s.proxies = proxies
r = s.get('https://api.ipify.org?format=json').json()
print(r['ip'])
import urllib.request
def set_http_proxy(proxy):
    if proxy == None: # Use system default setting
        proxy_support = urllib.request.ProxyHandler()
    elif proxy == '': # Don't use any proxy
        proxy_support = urllib.request.ProxyHandler({})
    else: # Use proxy
        proxy_support = urllib.request.ProxyHandler({'http': '%s' % proxy, 'https': '%s' % proxy})
    opener = urllib.request.build_opener(proxy_support)
    urllib.request.install_opener(opener)

proxy = 'user:pass@ip:port'
set_http_proxy(proxy)

url  = 'https://www.httpbin.org/ip'
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
html = response.read()
html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM