requests模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import requests res = requests.get('https://wpblog.x0y1.com')
print(res.text) if res.status_code == 200: print('请求成功') else: print('请求失败')
res = requests.get('https://apiv3.shanbay.com/codetime/articles/mnvdu')
with open('孔乙己.txt', 'w' ,encoding='utf8') as file: file.write(res.text)
res = requests.get('https://assets.baydn.com/baydn/public/codetime/xiaobei/info.jpg')
with open('info.jpg', 'wb') as file:
file.write(res.content)
|
变量 res它的类型是 Response 对象
属性 |
含义 |
res.status_code |
响应的 HTTP 状态码 |
res.text |
响应内容的字符串形式 |
res.content |
响应内容的二进制形式 |
res.encoding |
响应内容的编码 |
爬虫初体验
目标:自动循环小王子的所有章节,将故事存放到一个目录当中,每个章节一份文件。title做为文件名
1 2 3 4 5 6 7 8 9
| import requests
res = requests.get('http://www.eywedu.net/xiaowangzi/14.htm') res.encoding='gb2312' text = res.text
with open ('小王子.txt','w',encoding='utf8') as file: file.write(text)
|