【问题标题】:urllib.request with socks5 proxy?带有 socks5 代理的 urllib.request?
【发布时间】:2020-09-19 16:19:39
【问题描述】:

我想在我的代码中使用 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

【问题讨论】:

    标签: python python-3.x web-scraping urllib socks


    【解决方案1】:

    您需要将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())
    

    【讨论】:

      猜你喜欢
      • 2018-07-28
      • 2011-03-16
      • 2014-08-06
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      相关资源
      最近更新 更多