python request模块下载_python中的Requests模块
講解對(duì)象:python中的Requests模塊
作者:融水公子 rsgz
介紹:
1 Requests 是一個(gè)第三方 Python 模塊
2?Requests 唯一的一個(gè)非轉(zhuǎn)基因的 Python HTTP 庫(kù),人類可以安全享用
3?我們使用 pip3 安裝它
危險(xiǎn):
1 非專業(yè)使用其他 HTTP 庫(kù)會(huì)導(dǎo)致危險(xiǎn)的副作用
2 副作用:安全缺陷癥、冗余代碼
流程:
1 更新軟件列表
$ sudo apt-get update ?#更新軟件列表
2?安裝pip3
執(zhí)行命令:sudo apt-get install python3-pip
3?pip3安裝requests模塊
執(zhí)行命令:sudo pip3 install requests
4 進(jìn)入shell交互模式
命令:python3
5導(dǎo)入requests模塊
命令:import requests
6?get() 方法獲取網(wǎng)頁(yè)
命令:
req = requests.get('https://github.com')
req.status_code
擴(kuò)展:
1?req 的 text 屬性存有服務(wù)器返回的 HTML 網(wǎng)頁(yè)
2 這個(gè)知識(shí)叫我們 從指定的 URL 中下載文件
7 退出交互式
執(zhí)行命令:qiut()
8?當(dāng)前路徑新建文件
命令:vim download.py
9 vim編輯器進(jìn)入插入模式
命令:i
10輸入下面代碼
作用:從指定的 URL 中下載文件
#!/usr/bin/env python3
import requests
def download(url):
'''
從指定的 URL 中下載文件并存儲(chǔ)到當(dāng)前目錄
url: 要下載頁(yè)面內(nèi)容的網(wǎng)址
'''
# 檢查 URL 是否存在
try:
req = requests.get(url)
except requests.exceptions.MissingSchema:
print('Invalid URL "{}"'.format(url))
return
# 檢查是否成功訪問了該網(wǎng)站
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.")
#作為腳本執(zhí)行的時(shí)候)才會(huì)執(zhí)行此 if 塊內(nèi)的語(yǔ)句
if __name__ == '__main__':
url = input('Enter a URL: ')
download(url)
11 退出保存
esc
:wq
12 查看當(dāng)前文件列表
命令:ls
13 賦予可執(zhí)行權(quán)限
命令:chmod +x download.py
14 執(zhí)行腳本
命令:./download.py
15 界面提示:enter a url
16 百度圖片中搜索關(guān)鍵字 ?少司命
17 對(duì)準(zhǔn)目標(biāo)圖片點(diǎn)擊這個(gè)下載標(biāo)志
18 彈出的界面中 復(fù)制圖片的下載地址
網(wǎng)址:
19enter a url后面輸入圖片網(wǎng)址
命令:
20?目錄下已經(jīng)多了一個(gè) 圖片文件
總結(jié)
以上是生活随笔為你收集整理的python request模块下载_python中的Requests模块的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 重装系统 2021年最新方法 win10
- 下一篇: Python爬虫编程思想(92):项目实