分享

python中的Requests模块

 融水公子 2019-07-04

讲解对象:python中的Requests模块

作者:融水公子 rsgz


介绍

1 Requests 是一个第三方 Python 模块

2 Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用

3 我们使用 pip3 安装它


危险

1 非专业使用其他 HTTP 库会导致危险的副作用

2 副作用:安全缺陷症、冗余代码


流程:

1 更新软件列表

$ sudo apt-get update  #更新软件列表

安装pip3

执行命令:sudo apt-get install python3-pip  

pip3安装requests模块

执行命令:sudo pip3 install requests

4 进入shell交互模式

命令:python3


5 导入requests模块

命令:import requests


 get() 方法获取网页

命令:

req = requests.get('https://github.com')

req.status_code

扩展:

1 req 的 text 属性存有服务器返回的 HTML 网页

2 这个知识叫我们 从指定的 URL 中下载文件


7 退出交互式

执行命令:qiut()

当前路径新建文件

命令: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%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201707%2F15%2F20170715010216_3fRNC.thumb.700_0.jpeg&thumburl=http%3A%2F%2Fimg5.imgtn.bdimg.com%2Fit%2Fu%3D2950661776%2C984126073%26fm%3D26%26gp%3D0.jpg


19 enter a url后面输入图片网址

命令:

20 目录下已经多了一个 图片文件

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多