Setting proxy to urllib.request (Python3)

后端 未结 4 1407
攒了一身酷
攒了一身酷 2021-01-02 09:05

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)          


        
4条回答
  •  無奈伤痛
    2021-01-02 09:58

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

提交回复
热议问题