# !/usr/bin/python3 # -*-coding:UTF-8-*- import socket def web_connect(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建一个IPv4的socket s.connect(('www.sina.com.cn', 80)) # 建立与服务器源地址(host, port)的连接 s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n') # 接收数据: buffer = [] # 缓冲容器 while True: d = s.recv(1024) # recv(max)每次最多接收1k字节 if d: buffer.append(d) else: # 空数据,退出 break data = b''.join(buffer) # 连接字节数据 s.close() # 关闭连接 header, html = data.split(b'\r\n\r\n', 1) # HTTP头和网页分离 print(header.decode('utf-8')) with open('sina.html', 'wb') as f: # 接收的数据写入文件 f.write(html) if __name__ == '__main__': web_connect()
运行结果:
D:\Python37\python.exe D:/Python37/Code/socket_connect.py HTTP/1.1 302 Moved Temporarily Server: nginx Date: Wed, 07 Aug 2019 16:26:02 GMT Content-Type: text/html Content-Length: 154 Connection: close Location: https://www.sina.com.cn/ X-Via-CDN: f=edge,s=ctc.xiamen.ha2ts4.43.nb.sinaedge.com,c=119.133.210.176; X-Via-Edge: 1565195162639b0d285773cd64cde1bae90ce 进程已结束,退出代码 0
还没有学会SSL的编写。
Sign in to make a reply
ywjco_567
运行结果: