网络请求
1.服务端
from socket import socket, SOCK_STREAM, AF_INET
from datetime import datetime
def main():
server = socket(family=AF_INET, type=SOCK_STREAM)
server.bind(('10.7.185.90', 3458))
server.listen(512)
print('服务器启动开始监听...')
while True:
client, addr = server.accept()
print(str(addr) + '连接到了服务器.')
while True:
in_msg = client.recv(1024).decode('utf-8')
print(in_msg)
if in_msg == 'bye':
break
out_msg = input('请输入: ')
client.send(out_msg.encode('utf-8'))
client.close()
if __name__ == '__main__':
main()
2.客户端
from socket import socket, AF_INET, SOCK_STREAM
def main():
client = socket()
client.connect(('10.7.185.90', 3458))
while True:
out_msg = input('请输入: ')
client.send(out_msg.encode('utf-8'))
if out_msg == 'bye':
break
in_msg = client.recv(1024).decode('utf-8')
print(in_msg)
client.close()
if __name__ == '__main__':
main()
3.请求网络
import requests
def main():
url = 'https://www.apiopen.top/satinApi?type=1&page=1'
result = requests.get('https://www.apiopen.top/satinApi', params={'type': 1, 'page': 1})
print(result.text)
r_dict = result.json()
print(r_dict['msg'])
print(result.content)
result = requests.get('http://wimg.spriteapp.cn/profile/large/2017/03/01/58b6ed2126d85_mini.jpg')
data = result.content
with open('dog.jpg', 'wb') as ff:
ff.write(data)
print('图片下载完成')
if __name__ == '__main__':
main()
练习:下载该网页所有profile_image中的图片
import requests
url = 'https://www.apiopen.top/satinApi?type=1&page=1'
result = requests.get(url)
print(result.text)
r_dict = result.json()
print(r_dict['msg'])
for key in r_dict['data']:
url1 = (key['profile_image'])
resp = requests.get(url1)
filename = url1[url1.rfind('/') + 1:]
with open(filename, 'wb') as f:
f.write(resp.content)
print('图片下载完成!')