python socket 模拟http请求


	python socket 模拟http请求
[编程语言教程]

 

 

# coding: utf-8
import socket
from urllib.parse import urlparse


def get_url(url):
    url = urlparse(url)
    host = url.netloc
    path = url.path

    if path == "":
        path = "/"

    # 建立 socket 连接
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((host, 80))

    client.send("GET {} HTTP/1.1
Host:{}
Connection:close

".format(path, host).encode("utf-8"))

    data = b""
    while True:
        d = client.recv(1024)
        if d:
            data += d
        else:
            break

    data = data.decode("utf-8")
    html_data = data.split("

")[1]
    print(html_data)
    client.close()
    pass


if __name__ == ‘__main__‘:
    get_url("http://www.baidu.com")
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » python socket 模拟http请求