Skip to content

Commit b0e05bd

Browse files
committed
网络请求模块-urllib(python3)
1 parent d343cea commit b0e05bd

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

网络请求模块的使用.md

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ req = urllib2.Request(
3636
#2.4. 发送请求
3737
resp = urllib2.urlopen(req)
3838
#3. 处理响应内容
39-
with open("text.txt", "wb", encoding="utf-8") as f:
39+
with open("text.txt", "wb") as f:
4040
f.write(resp.read())
4141
4242
@@ -45,3 +45,32 @@ with open("text.txt", "wb", encoding="utf-8") as f:
4545
## urllib
4646
> python3 中使用urllib网络库
4747
48+
```python3
49+
#!/usr/bin/python3
50+
# -*- coding: utf-8 -*-
51+
import urllib.request
52+
53+
# 2. 发起网络请求
54+
# 2.1. 定义请求地址
55+
url = "https://github.com"
56+
# 2.2. 自定义请求头
57+
headers = {
58+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
59+
"Referer": "https://github.com/",
60+
"Host": "github.com"
61+
}
62+
63+
# 定义请求对象
64+
req = urllib.request.Request(
65+
url=url,
66+
headers=headers
67+
)
68+
69+
# 发送请求
70+
resp = urllib.request.urlopen(req)
71+
72+
# 处理响应
73+
with open('github.txt', 'wb') as f:
74+
f.write(resp.read())
75+
```
76+

0 commit comments

Comments
 (0)