python urllib socks5 auth username password 設定

Cocktail_py發表於2020-12-15

在使用一批socks5帶使用者名稱和密碼的代理的時候需要用到urllib這個python庫

# https://pypi.org/project/PySocks/
import urllib
import socks
import socket
# from urllib import request
from urllib.error import URLError
username = "username"
password = "password"
ip = "107.*.*.122"
port = 11336
proxy = "socks5://{username}:{password}@{ip}:{port}".format(username=username,password=password,ip=ip,port=port)
socks.set_default_proxy(socks.SOCKS5, ip, port,username=username,password=password)
socket.socket = socks.socksocket

url = 'http://httpbin.org/get'
try:
    req = urllib.request.Request(url=url,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'})
    response = urllib.request.urlopen(req)
    # response = request.urlopen(url)
    print(response.read().decode('utf-8'))
except URLError as e:
    print(e)
// 相應結果
{
  "args": {}, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Host": "httpbin.org", 
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36", 
    "X-Amzn-Trace-Id": "Root=1-5fd8a0d5-6f4cb76331f614657da833e8"
  }, 
  "origin": "107.*.*.122", 
  "url": "http://httpbin.org/get"
}

參考:https://pypi.org/project/PySocks/

相關文章