简体   繁体   中英

Python3 - Requests with Sock5 proxy

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)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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