美文网首页
10-2 socket实现http的get

10-2 socket实现http的get

作者: 正在努力ing | 来源:发表于2018-08-26 15:37 被阅读0次
    import socket
    from urllib.parse import urlparse
    
    def get_url(url):
        url = urlparse(url)
        host = url.netloc
        path = url.path
        if path == "":
            path = "/"
    
    
        client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        client.connect((host,80))
    
        # http 规定好的发报格式
        client.send("GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n".format(path, host).encode("utf8"))
    
        data = b""
        while True:
            d = client.recv(1024)
            if d:
                data += d
            else:
                break
    
        data = data.decode("utf8")
        html_data = data.split("\r\n\r\n")[1]
        print(html_data)
        client.close()
    
    
    if __name__ == "__main__":
        url = "http://www.baidu.com"
        get_url(url)
    
    

    相关文章

      网友评论

          本文标题:10-2 socket实现http的get

          本文链接:https://www.haomeiwen.com/subject/qxyoiftx.html