非阻塞IO HTTP请求

import socket
from urllib.parse import urlparse


# 通过socket请求html
# 非阻塞IO完成http请求
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.setblocking(False)
    try:
        client.connect((host, 80))
    except BlockingIOError as e:
        pass

    while True:
        try:
            client.send("GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n".format(path, host).encode("utf8"))
            break
        except OSError as e:
            pass

    data = b""
    while True:
        try:
            d = client.recv(1024)
        except BlockingIOError as e:
            continue
        if d:
            data += d
        else:
            break

    data = data.decode("utf8")
    html_data = data.split("\r\n\r\n")[1:]
    print("\r\n\r\n".join(html_data))
    client.close()


if __name__ == "__main__":
    get_url("http://www.baidu.com")

 

posted on 2021-01-11 19:17  文艺青年.茶  阅读(103)  评论(0编辑  收藏  举报

导航