发布时间:2021-02-22 点击数:188
讲解对象:python中的Requests模块
作者:融水公子 rsgz
介绍:
1 Requests 是一个第三方 Python 模块
2 Requests 唯一的一个非转基因的 Python HTTP 库,人类能够坦然享用
3 吾们行使 pip3 装配它
危险:
1 非专科行使其他 HTTP 库会导致危险的副作用
2 副作用:坦然弱点症、冗余代码
流程:
1 更新柔件列外
$ sudo apt-get update #更新柔件列外
图片
2 装配pip3
实走命令:sudo apt-get install python3-pip
图片
3 pip3装配requests模块
实走命令:sudo pip3 install requests
图片
4 进入shell交互模式
命令:python3
图片
5 导入requests模块
命令:import requests
图片
6 get() 手段获取网页
命令:
req = requests.get('https://github.com')
req.status_code
图片
扩展:
1 req 的 text 属性存有服务器返回的 HTML 网页
2 这个知识叫吾们 从指定的 URL 中下载文件
7 退出交互式
实走命令:qiut()
图片
8 现在路径新建文件
命令:vim download.py
图片
9 vim编辑器进入插入模式
命令:i
图片
10 输入下面代码
作用:从指定的 URL 中下载文件
#!/usr/bin/env python3
import requests
def download(url):
'''
从指定的 URL 中下载文件并存储到现在现在录
url: 要下载页面内容的网址
'''
# 检查 URL 是否存在
try:
req = requests.get(url)
except requests.exceptions.MissingSchema:
print('Invalid URL "{}"'.format(url))
return
# 检查是否成功访问了该网站
if req.status_code == 403:
print('You do not have the authority to access this page.')
return
filename = url.split('/')[-1]
with open(filename, 'w') as fobj:
fobj.write(req.content.decode('utf-8'))
print("Download over.")
#行为脚本实走的时候)才会实走此 if 块内的语句
if __name__ == '__main__':
url = input('Enter a URL: ')
download(url)
图片
11 退出保存
esc
:wq
图片
12 查望现在文件列外
命令:ls
图片
13 授予可实走权限
命令:chmod +x download.py
图片
14 实走脚本
命令:./download.py
图片
15 界面挑示:enter a url
图片
16 百度图片中搜索关键字 少司命
图片
17 对准现在的图片点击这个下载标志
图片
18 弹出的界面中 复制图片的下载地址
图片
网址:
http://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=http://b-ssl.duitang.com/uploads/item/201707/15/20170715010216_3fRNC.thumb.700_0.jpeg&thumburl=http://img5.imgtn.bdimg.com/it/u=2950661776,欧宝OBO984126073&fm=26&gp=0.jpg
19 enter a url后面输入图片网址
命令:
图片
20 现在录下已经众了一个 图片文件
,