import socket标签:sockaddr,socket,af,python,res,爬虫,content,print From: https://www.cnblogs.com/lld76/p/16748470.html
# 第一步 获取域名或ip地址
host = 'www.baidu.com'
port = 80
header = b'GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: close\r\n\r\n'
# 第二步 域名解析 将url(网址)转换为ip地址
for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
# print(res)
af, socktype, proto, canonname, sockaddr = res
print(af, socktype, proto, canonname, sockaddr)
s = socket.socket(af, socktype)
s.connect(sockaddr)
# 第三步 发送数据
with s:
s.send(header)
content = []
while 1:
t = s.recv(1024)
if t:
content.append(t.decode('utf-8'))
else:
break
c = ''.join(content).encode()
print(c.decode())