当我们使用浏览器打开网页的时候,浏览器就是一个客户端,浏览器也会创建socket对象与要访问的网站建立连接。

下面一个例子简单实现了基于tcp协议的访问百度并保存成html文件的功能

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('www.baidu.com', 80))
sock.send(b'GET / HTTP/1.1\r\nHOST: www.baidu.com\r\nConnection:close\r\n\r\n')

buffer = []
while True:
    content = sock.recv(1024)   #以1024字节(1kb)为一个单位进行接收,直到完全接收所有数据。
    if content:
        buffer.append(content)
    else:
        break

web_content = b''.join(buffer)

#分割http协议头,保存的html文件不包含http协议头
http_header, http_content = web_content.split(b'\r\n\r\n', 1)

with open('baidu.com.html', 'wb') as f:
    f.write(http_content)

你也可能喜欢

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注