模拟浏览器请求web服务器的网页过程,使用TCP实现http协议
python
# 1 、导入模块
import socket
# 2 、创建套接字
tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 3·建立连接
tcp_client_socket.connect(("www.icoderi.com", 80))
# 4﹑拼接请求协议
# 4.1请求行
request_line = "GET / HTTP/1.1\r\n"
# 4.2请求头
request_header = "Host:www.icoderi.com\r\n"
# 4.3请求空行
request_blank = "\r\n"
request_data = request_line + request_header + request_blank
# 5﹑发送请求协议
tcp_client_socket.send(request_data.encode())
# 6·接收服务器响应内容(4kb)
recv_data = tcp_client_socket.recv(4096)
# 7﹑保存内容
recv_text = recv_data.decode()
# 7.1截取字符串取<html>
loc = recv_text.find("\r\n\r\n")
html_data = recv_text[loc + 4:]
print(html_data)
# 7.2保存文本内容
with open("index.html", "w") as file:
file.write(html_data)
# 8·关闭连接
tcp_client_socket.close()