Skip to content

Commit a5903ca

Browse files
committed
完善http模块文档
1 parent 5b143ee commit a5903ca

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

http模块.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,34 @@
11
# http模块 #
2+
python中的http/https请求使用urllib库,使用urllib的request模块的发送get和post请求。
3+
4+
## get请求 ##
5+
请求网页地址并返回网页html内容,示例如下:
6+
```
7+
from urllib import request
8+
9+
10+
def getHtml(url):
11+
with request.urlopen(url) as r:
12+
data = r.read()
13+
return data.decode("utf-8")
14+
15+
16+
print(getHtml("http://vipstone.cnblogs.com"))
17+
```
18+
对返回的数据进行编码处理data.decode("utf-8")即可。
19+
20+
## post请求 ##
21+
post请求并传递参数,对参数进行encode处理,示例如下:
22+
```
23+
from urllib import request, parse
24+
25+
26+
params = parse.urlencode([("name", "老王"), ("pwd", "123456")])
27+
req = request.Request("http://127.0.0.1:8360/video/login")
28+
req.add_header("User-Agent", "Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25")
29+
30+
with request.urlopen(req, data=params.encode("utf-8")) as r:
31+
data = r.read()
32+
print(data.decode("utf-8"))
33+
```
34+
如上所示,需要使用urllib的parse对参数进行编码处理,也可以给http头添加内容。

0 commit comments

Comments
 (0)