码迷,mamicode.com
首页 > 编程语言 > 详细

python socket 模拟http请求

时间:2020-08-02 16:13:18      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:请求   模拟   span   for   +=   decode   soc   form   htm   

 

 

# 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\r\nHost:{}\r\nConnection:close\r\n\r\n".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("\r\n\r\n")[1]
    print(html_data)
    client.close()
    pass


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

 

python socket 模拟http请求

标签:请求   模拟   span   for   +=   decode   soc   form   htm   

原文地址:https://www.cnblogs.com/angdh/p/13418586.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!