Discuss / Python / ssl.wrap_socket()已经不能用了

ssl.wrap_socket()已经不能用了

Topic source

立冬前后

#1 Created at ... [Delete] [Delete and Lock User]

改成这样即可:

  7 import socket

  8 import ssl

  9 # client端

 10 hostname = 'www.baidu.com'

 11 context = ssl.create_default_context()

 12 with socket.create_connection((hostname, 443)) as s:

 13     with context.wrap_socket(s, server_hostname=hostname) as ss:

 14        

 15

 16         ss.send(b'GET / HTTP/1.1\r\nHOST: www.baidu.com\r\nConnection: close\r\n\r\n')

 17         buffer = []                             # 获取网页数据的列表

 18         while True:

 19             d = ss.recv(1024)

 20             if d:

 21                 buffer.append(d)

 22             else:

 23                 break

 24         data = b''.join(buffer)                 # 列表转字符串

 25         header, html = data.split(b'\r\n\r\n', 1)

 26         print(header.decode('utf-8'))

 27         with open('baidu.html', 'wb') as f:

 28             f.write(html)


  • 1

Reply