美文网首页
socket 模拟http请求

socket 模拟http请求

作者: ___大鱼___ | 来源:发表于2019-06-04 10:22 被阅读0次
# coding: utf-8

import socket
from urlparse import urlparse


def get_url(url):
    # 通过socket请求html
    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\r\nHOST:{}\r\nConnection:close\r\n\r\n'.format(path, host).encode('utf8'))
    data = b''
    while 1:
        d = client.recv(1024)
        if d:
            data += d
        else:
            break
    data = data.decode('utf8')
    print data
    client.close()


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

相关文章

网友评论

      本文标题:socket 模拟http请求

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