1. 程式人生 > 其它 >requests模組基礎(一)

requests模組基礎(一)

技術標籤:Python

requests模組:python中原生的一款基於網路請求的模組,功能非常強大,簡單便捷,效率極高。
作用:模擬瀏覽器發請求。

如何使用:(requests模組的編碼流程)
- 指定url
- UA偽裝
- 請求引數的處理
- 發起請求
- 獲取響應資料
- 持久化儲存

環境安裝:
pip install requests

實戰編碼:
- 需求:爬取搜狗首頁的頁面資料

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
#- 需求:爬取搜狗首頁的頁面資料
import requests
if __name__ == "__main__"
: #step_1:指定url url = 'https://www.sogou.com/' #step_2:發起請求 #get方法會返回一個響應物件 response = requests.get(url=url) #step_3:獲取響應資料.text返回的是字串形式的響應資料 page_text = response.text print(page_text) #step_4:持久化儲存 with open('./sogou.html','w',encoding='utf-8') as fp: fp.
write(page_text) print('爬取資料結束!!!')