Python3 - Requests with Sock5 proxy

17,191

Solution 1

You can use socks, socket modules

import socks
import socket
from urllib import request
socks.set_default_proxy(socks.SOCKS5, "localhost", 9050)
socket.socket = socks.socksocket
r = request.urlopen('http://icanhazip.com')
print(r.read()) # check ips

The socks package can be installed from multiple packages which are forks of socksipy. One particular one that also works on Python3 is PySocks. You can install it, for example, with pip:

pip3 install PySocks

Solution 2

I think at the moment requests works with socks5 out of the box.

import requests
url = 'https://example.com'
proxies = {'http': 'socks5://127.0.0.1:9150',
           'https': 'socks5://127.0.0.1:9150'}
r = requests.get(url, proxies=proxies)
Share:
17,191

Related videos on Youtube

Bob Ebert
Author by

Bob Ebert

Updated on June 25, 2022

Comments

  • Bob Ebert
    Bob Ebert 11 months

    Is there a way to use sock5 proxy to use TOR with requests? I know that requests only use http proxy...

    import requests
    r = requests.get('http://www.google.com',proxies= my_proxy)
    
  • Yassir S
    Yassir S about 5 years
    It doesn't work for me on windows. I don't understand why. Do you have an idean on what I should investigate ?
  • Bibek Ghimire
    Bibek Ghimire about 5 years
    raise GeneralProxyError("Connection closed unexpectedly")
  • Masood Khaari
    Masood Khaari over 1 year
    It needs pip install "requests[socks]" too.

Related