ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
上节课,我们学习了什么是网络、网络的发展历程和常见网络协议。这节课,我们重点学习一下HTTP协议和怎么用python请求、解析HTTP数据。 ## 什么是HTTP ![](https://www.simplilearn.com/ice9/blog/wp-content/uploads/2014/12/Why-HTML-is-important-for-content-writers.gif) HTTP是**超文本传输协议**的简称。所谓**超文本**,就是在互联网上传输的信息。我们在浏览器里浏览的网页,就是使用超文本标记语言HTML实现的,下章我们会详细介绍HTML。 ![](http://2.bp.blogspot.com/_4l9wMe5bbSk/TMpvwVcMT3I/AAAAAAAAAK4/sCEjRQCkF1o/s1600/Client+Server+communication.GIF) 典型的HTTP传输如下:客户端(浏览器)对指定的url发起http请求。url指定的服务端在接收到请求后,将自己的数据(经常是html或json)返回给客户端。 我们分别看一下发起请求和请求响应的部分。 一个典型的请求头如下: ~~~ GET / HTTP/1.0 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) Accept: */* ~~~ ![](https://www.safaribooksonline.com/library/view/restful-net/9780596155025/httpatomoreillycomsourceoreillyimages224471.png) 我们去请求服务端数据时,有`get`,`post`,`put`,`delete`4种方式,其中 get和post较为常用。 请求的响应数据格式如下: ~~~ HTTP/1.0 200 OK Content-Type: text/plain Content-Length: 137582 Expires: Thu, 05 Dec 1997 16:00:00 GMT Last-Modified: Wed, 5 August 1996 15:55:28 GMT Server: Apache 0.84 <html> <body>Hello World</body> </html> ~~~ 回应的格式是"头信息 + 一个空行(\r\n) + 数据"。其中,第一行是"协议版本 + 状态码(status code) + 状态描述"。 这里有个非常重要的,状态码。具体含义如下: ![](http://aviraer.info/images/2018/HTTP%E7%8A%B6%E6%80%81%E7%A0%81%E7%B1%BB%E5%88%AB.png) ## 什么是URL ## python的request模块 在python中,我们使用`requests`模块来发起发起http请求。 1. request 安装 我们可以使用`pip install requests`命令安装requests包。 2. 请求数据demo ~~~ r = requests.get('https://api.github.com/events') ~~~ 调用 requests的get方法发起请求,请求参数是目标地址。 3. post请求的参数 post请求时的附带参数可以这样模拟: ~~~ requests.post('http://baidu.com', data = {'key':'value'}) ~~~ get请求的参数 ~~~ payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get("http://baidu.com", params=payload) print(r.url) ~~~ 4. 获取请求返回数据 ~~~ r = requests.get('https://api.github.com/events') print(r.text) ~~~ 5. 返回结果json解码 ~~~ r = requests.get('https://api.github.com/events') print(r.json()) ~~~ 6. 设置超时(秒单位) ~~~ requests.get('http://github.com', timeout=3) ~~~ ## 代码实例 下面,我们来看一个python通过http请求获取天气的小demo,看代码: ~~~ import requests from tkinter import * def queryWeather(): city = cityEntry.get() headers = {'Authorization': 'APPCODE 2c571bbe36b24e9aa3cadaaee4d0adbf'} r = requests.get( 'https://saweather.market.alicloudapi.com/spot-to-weather?area='+city+'&need3HourForcast=0&needAlarm=0&needHourData=0&needIndex=0&needMoreDay=0', headers=headers) weather = r.json()['showapi_res_body']['now']['weather'] weatherLabel = Label(root, text=weather) weatherLabel.pack() return weather root=Tk() cityEntry = Entry(root) cityEntry.pack() button = Button(root,text='查询天气', command=queryWeather) button.pack() root.mainloop() ~~~ 代码的第二行,我们往http的header里设置了请求码,用来做鉴权。当获得数据后,我们首先将结果转为json格式。然后读取返回数据的当前天气字段。 request模块里还有更多的方法来发起复杂HTTP请求,我们在具体项目使用时再一起学习。 **阿达老师-孩子身边的编程专家** *完整课程请关注阿达老师,主页里有完整的课程目录和观看地址*