通过Python发送HTML

2024-03-28 10:46:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试学习一些HTTP/CGI的内容,当您在浏览器中查看网页时,我想在网页上打印HTML,但不确定使用socket库时的正确语法是什么:

#!/usr/bin/env python
import random
import socket
import time

s = socket.socket()         # Create a socket object
host = socket.getfqdn() # Get local machine name
port = 9082
s.bind((host, port))        # Bind to the port

print 'Starting server on', host, port
print 'The Web server URL for this would be http://%s:%d/' % (host, port)

s.listen(5)                 # Now wait for client connection.

print 'Entering infinite loop; hit CTRL-C to exit'
while True:
    # Establish connection with client.    
    c, (client_host, client_port) = s.accept()
    print 'Got connection from', client_host, client_port
    c.send('Server Online\n')
    c.send('HTTP/1.0 200 OK\n')
    c.send('Content-Type: text/html\n')
    c.send(' """\
        <html>
        <body>
        <h1>Hello World</h1> this is my server!
        </body>
        </html>
        """ ')
    c.close()

前三个c.send行起作用,然后最后一行我放在HTML中时出现语法问题。


Tags: toimportclientsendhttphost网页server
1条回答
网友
1楼 · 发布于 2024-03-28 10:46:00

使用三引号字符串:

c.send("""
    <html>
    <body>
    <h1>Hello World</h1> this is my server!
    </body>
    </html>
""") # Use triple-quote string.

除了语法错误,代码中还有多个问题。下面是一个修改过的版本(仅当循环时,请参阅注释以查看所做的修改)

while True:
    # Establish connection with client.    
    c, (client_host, client_port) = s.accept()
    print 'Got connection from', client_host, client_port
    #c.send('Server Online\n') # This is invalid HTTP header
    c.recv(1000) # should receive request from client. (GET ....)
    c.send('HTTP/1.0 200 OK\n')
    c.send('Content-Type: text/html\n')
    c.send('\n') # header and body should be separated by additional newline
    c.send("""
        <html>
        <body>
        <h1>Hello World</h1> this is my server!
        </body>
        </html>
    """) # Use triple-quote string.
    c.close()

相关问题 更多 >