带有Socks5代理的urllib.request吗?

问题描述

我想在代码中使用socks5代理。该怎么做?

我的代码:

from urllib.request import Request,urlopen
url = "https://api.ipify.org/"
request = Request(url)
response = urlopen(request)

print(response.read())

此外,我可以说使用http / https代理服务器
我做到了: request.set_proxy(proxy_address,"http") 之前
response = urlopen(url),但现在不起作用。

编辑
我发现了那样的东西

from urllib.request import Request,urlopen
import socks
import socket

request = Request("https://api.ipify.org/")
socks.set_default_proxy(socks.SOCKS5,IP_ADDR,PORT)
socket.socket = socks.socksocket
response = urlopen(request)

print(response.read())

但这给了我
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain

解决方法

您需要将 urllib.request.urlopencustom ssl context 一起使用:link here

import socks
import socket
import ssl
from urllib.request import Request,urlopen

IP_ADDR = '127.0.0.1'
PORT = 9050
url = "http://httpbin.org/ip"

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

request = Request(url)
socks.set_default_proxy(socks.SOCKS5,IP_ADDR,PORT)
socket.socket = socks.socksocket
response = urlopen(request,context=ctx)

print(response.read())

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...