首页 > 解决方案 > 如何使用 python 套接字修复 301 错误

问题描述

我刚刚开始学习如何在 python 中使用套接字。我正在尝试创建对“python.org”的获取请求,但我不断收到“301”错误。如果有人知道为什么请帮忙。

import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
        request = 'GET / HTTP/1.1\r\nHost:%s\r\n\r\n' % hostname
        ssock.send(request.encode())
        response = ssock.recv(6000)
        print(response)

编辑:我目前收到此回复

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)

任何人都可以帮助解决这个错误吗?

得到它使用此代码:

import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:

    try:
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
    except:
        None

    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())
        request = 'GET / HTTP/1.1\r\nHost:%s\r\n\r\n' % hostname
        ssock.send(request.encode())
        response = ssock.recv(6000)
        print(response)

标签: pythonsocketshttphttps

解决方案


301 HTTP 代码被永久移动不是错误。对于此资源,您需要与另一个链接一起使用(当前为/,它在第一行中定义GET / HTTP)。它在您的回复中定义http_response


推荐阅读