Python的Requets模块

Requests 是一个第三方 Python 模块,其官网的介绍如下:

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

警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症、冗余代码症、重新发明轮子症、啃文档症、抑郁、头疼、甚至死亡。

第三方模块并不是默认的模块,意味着你需要安装它,我们使用 pip3 安装它。

首先要安装 pip3

sudo apt-get update
sudo apt-get install python3-pip

利用pip3安装requests模块

sudo pip3 install requests

示例:

1、获得简单的网页

2、下载文件的程序

!/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 name == 'main':
     url = input('Enter a URL: ')
     download(url)

发表评论

后才能评论