網站首頁 編程語言 正文
Python 網絡請求模塊 urllib 、requests
Python 給人的印象是抓取網頁非常方便,提供這種生產力的,主要依靠的就是 urllib、requests這兩個模塊。
urlib 介紹
- urllib.request 提供了一個 urlopen 函數,來實現獲取頁面。支持不同的協議、基本驗證、cookie、代理等特性。
- urllib 有兩個版本 urllib 以及 urllib2。
- urllib2 能夠接受 Request 對象,urllib 則只能接受 url。
- urllib 提供了 urlencode 函數來對GET請求的參數進行轉碼,urllib2 沒有對應函數。
- urllib 拋出了 一個 URLError 和一個 HTTPError 來處理客戶端和服務端的異常情況。
Requests 介紹
Requests 是一個簡單易用的,用Python編寫的HTTP庫。這個庫讓我們能夠用簡單的參數就完成HTTP請求,而不必像 urllib 一樣自己指定參數。同時能夠自動將響應轉碼為Unicode,而且具有豐富的錯誤處理功能。
- International Domains and URLs
- Keep-Alive & Connection Pooling
- Sessions with Cookie Persistence
- Browser-style SSL Verification
- Basic/Digest Authentication
- Elegant Key/Value Cookies
- Automatic Decompression
- Unicode Response Bodies
- Multipart File Uploads
- Connection Timeouts
- .netrc support
- List item
- Python 2.6—3.4
- Thread-safe
以下為一些示例代碼,本文環境為 Python 3.6
無需參數直接請求單個頁面
import urllib
from urllib.request import request
from urllib.urlopen import urlopen
# import urllib2
import requests
# 使用 urllib 方式獲取
response = urllib.request.urlopen('http://www.baidu.com')
# read() 讀取的是服務器的原始返回數據 decode() 后會進行轉碼
print(response.read().decode())
# 使用 requests 方式獲取
# request 模塊相比
resp = requests.get('http://www.baidu.com')
print(resp)
print(resp.text)
HTTP 是基于請求和響應的工作模式,urllib.request 提供了一個 Request 對象來代表請求,因此上面的代碼也可以這么寫
req = urllib.request.Request('http://www.baidu.com')
with urllib.request.urlopen(req) as response:
print(response.read())
Request對象可以增加header信息
req = urllib.request.Request('http://www.baidu.com')
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
with urllib.request.urlopen(req) as response:
print(response.read())
或者直接將 header 傳入 Request 構建函數。
帶參數的 GET 請求
帶有參數的請求和上面的例子本質一樣,可以事先拼出URL請求字符串,然后再進行請求。
本例使用了 騰訊 的股票API,可以傳入不同的股票代碼以及日期,查詢對應股票在對應時間的價格、交易信息。
# 使用帶參數的接口訪問
tencent_api = "http://qt.gtimg.cn/q=sh601939"
response = urllib.request.urlopen(tencent_api)
# read() 讀取的是服務器的原始返回數據 decode() 后會進行轉碼
print(response.read())
resp = requests.get(tencent_api)
print(resp)
print(resp.text)
發送 POST 請求
urllib 沒有單獨區分 GET 和 POST 請求的函數,只是通過 Request 對象是否有 data 參數傳入來判斷。
import urllib.parse
import urllib.request
url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python' }
data = urllib.parse.urlencode(values)
data = data.encode('ascii') # data should be bytes req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
the_page = response.read()
原文鏈接:https://blog.csdn.net/qdPython/article/details/127184235
相關推薦
- 2022-04-25 django數據庫遷移migration實現_python
- 2022-04-01 kubeadm報錯:The connection to the server localhost:8
- 2022-04-02 在python3中使用Supervisor的詳細教程_python
- 2022-11-28 golang進程內存控制避免docker內oom_Golang
- 2022-06-16 C++新特性詳細分析基于范圍的for循環_C 語言
- 2022-04-12 Oracle同步數據到kafka的方法_oracle
- 2022-05-11 mac ssh 免密登錄 localhost
- 2022-10-12 docker配置阿里云鏡像倉庫的實現_docker
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支