1. 使用requests实现
import requests
r = requests.get('http://www.httpbin.org')
print (r.status_code)
print (r.headers)
200
{‘Date’: ‘Tue, 08 Dec 2020 09:41:06 GMT’, ‘Content-Type’: ‘text/html; charset=utf-8’, ‘Content-Length’: ‘9593’, ‘Connection’: ‘keep-alive’, ‘Server’: ‘gunicorn/19.9.0’, ‘Access-Control-Allow-Origin’: ‘*’, ‘Access-Control-Allow-Credentials’: ‘true’}
使用socket模块实现
# 用socket实现
import socket
#AF_INET:ipv4地址,SOCK_STREAM:tcp协议
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# debug
print(f's1:{s}')
s1:<socket.socket fd=1184, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0>
s.connect(('www.httpbin.org',80))
# debug
print (f's2:{s}')
s2:<socket.socket fd=1184, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(‘10.10.15.231’, 62066), raddr=(‘3.211.1.78’, 80)>
s.send(b'GET / HTTP/1.1\r\nHOST:time.geekbang.org\r\nConnection: close\n\r\n')
60
buffer = []
while True:
data = s.recv(1024)
if data:
buffer.append(data)
else:
break
s.close()
respose = b''.join(buffer)
header, html = respose.split(b'\r\n\r\n', 1)
print(header.decode('GBK'))
with open('index.html', 'wb') as f:
f.write(html)
HTTP/1.1 200 OK
Date: Tue, 08 Dec 2020 13:01:56 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 9593
Connection: close
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true