2017-07-24 20:43:49
The socket is also called a socket, and the application usually makes a request to the network through a "socket" or answers a network request. The main operational flow of the HTTP protocol is request-response, which is the request response. We can use the socket library in Python to build the connection, and then use the Get method to get the server-side data.
First, use the socket to get the Web page
ImportSocket#socket parameter declaration, without modification directly usingMysock =Socket.socket (Socket.af_inet,socket. SOCK_STREAM)#Establish socket connection, address plus port numberMysock.connect (('www.py4inf.com', 80))#According to the requirements of the HTTP protocol, the information sent must start with get, followed by the URL address + protocol + two line break, and finally because it is py3, so need to add encode ()Mysock.send ('GET http://www.py4inf.com/http/1.1\n\n'. Encode ()) whileTrue:#because it is py3, we need to add decode ()data = MYSOCK.RECV (512). Decode ()ifLen (data) <1: Break Print(data) mysock.close ()
Second, use the request library for network connection
This is very convenient, do not directly with the transport layer socket, directly to the URL of the GE method.
Import= requests.get ('http://jwc.seu.edu.cn/') Print(r.text)
Python Network programming and sockets