Use proxy in Python 3

5

I'm wanting to use a proxy connection in Python 3, something simple.

I would like an alternative to the method used in Python 2

proxy = {"http":"http://178.22.148.122:3129"}   
urllib.urlopen("http://httpbin.org/ip", proxies = proxy).read()

I try with

urllib.request.urlopen("http://httpbin.org/ip", proxies = proxy).read()

But he tells me:

  

Unexpected keyword argument 'proxies'

Thanks for your answers!

    
asked by boti likerino 30.03.2017 в 23:45
source

1 answer

3

This is one of the modules that changed quite a lot between the branch 2 and 3 of Python, there are several ways:

  • Using the class urllib.request.ProxyHandler , we created an opener using the previous instance and we installed it:

    from urllib import request
    
    proxies = {'http':"218.28.112.114:809"}
    url = 'http://www.httpbin.org/ip'
    
    proxy = request.ProxyHandler(proxies)
    opener = request.build_opener(proxy)
    request.install_opener(opener)
    response=request.urlopen(url)
    print(response.read().decode('utf8'))
    
  • We can also use the set_proxy :

    from urllib import request
    
    proxy_host = "218.28.112.114:809"
    url = 'http://www.httpbin.org/ip'
    
    req = request.Request(url)
    req.set_proxy(proxy_host, 'http')
    response = request.urlopen(req)
    print(response.read().decode('utf8'))
    
answered by 31.03.2017 в 00:42