• 非阻塞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
    Host:{}
    Connection:close
    
    ".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("
    
    ")[1:]
        print("
    
    ".join(html_data))
        client.close()
    
    
    if __name__ == "__main__":
        get_url("http://www.baidu.com")
  • 相关阅读:
    MVC过滤器
    MVC自带的校验
    FPGA简单概述
    CAN总线扩展数据帧介绍
    简述人工智能发展的先决条件
    CAN总线标准帧
    CAN总线应用
    CAN总线优点
    CAN总线概述
    高速PCB设计注意事项
  • 原文地址:https://www.cnblogs.com/yejing-snake/p/14263786.html
Copyright © 2020-2023  润新知