python socket 模拟http请求

Posted AngDH

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python socket 模拟http请求相关的知识,希望对你有一定的参考价值。

 

 

# 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
Host:{}
Connection:close

".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("

")[1]
    print(html_data)
    client.close()
    pass


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

 

以上是关于python socket 模拟http请求的主要内容,如果未能解决你的问题,请参考以下文章

Python模拟浏览器实现网页访问

java socket模拟http请求

使用PHP Socket 编程模拟Http post和get请求

C#怎么用Socket模拟 HTTP请求

socket模拟发送http请求

Socket 模拟HTTP客户端请求