
- Python 基礎
- Python - 首頁
- Python - 概覽
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World 程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境設定
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode 系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python 控制語句
- Python - 控制流
- Python - 決策
- Python - if 語句
- Python - if else
- Python - 巢狀 if
- Python - Match-Case 語句
- Python - 迴圈
- Python - for 迴圈
- Python - for-else 迴圈
- Python - while 迴圈
- Python - break 語句
- Python - continue 語句
- Python - pass 語句
- Python - 巢狀迴圈
- Python 函式 & 模組
- Python - 函式
- Python - 預設引數
- Python - 關鍵字引數
- Python - 僅關鍵字引數
- Python - 位置引數
- Python - 僅位置引數
- Python - 可變引數
- Python - 變數作用域
- Python - 函式註解
- Python - 模組
- Python - 內建函式
- Python 字串
- Python - 字串
- Python - 字串切片
- Python - 修改字串
- Python - 字串連線
- Python - 字串格式化
- Python - 跳脫字元
- Python - 字串方法
- Python - 字串練習
- Python 列表
- Python - 列表
- Python - 訪問列表項
- Python - 修改列表項
- Python - 新增列表項
- Python - 刪除列表項
- Python - 迴圈遍歷列表
- Python - 列表推導式
- Python - 排序列表
- Python - 複製列表
- Python - 合併列表
- Python - 列表方法
- Python - 列表練習
- Python 元組
- Python - 元組
- Python - 訪問元組項
- Python - 更新元組
- Python - 解包元組
- Python - 迴圈遍歷元組
- Python - 合併元組
- Python - 元組方法
- Python - 元組練習
- Python 集合
- Python - 集合
- Python - 訪問集合項
- Python - 新增集合項
- Python - 刪除集合項
- Python - 迴圈遍歷集合
- Python - 合併集合
- Python - 複製集合
- Python - 集合運算子
- Python - 集合方法
- Python - 集合練習
- Python 字典
- Python - 字典
- Python - 訪問字典項
- Python - 修改字典項
- Python - 新增字典項
- Python - 刪除字典項
- Python - 字典檢視物件
- Python - 迴圈遍歷字典
- Python - 複製字典
- Python - 巢狀字典
- Python - 字典方法
- Python - 字典練習
- Python 陣列
- Python - 陣列
- Python - 訪問陣列項
- Python - 新增陣列項
- Python - 刪除陣列項
- Python - 迴圈遍歷陣列
- Python - 複製陣列
- Python - 反轉陣列
- Python - 排序陣列
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python 檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS 檔案/目錄方法
- Python - OS 路徑方法
- 面向物件程式設計
- Python - OOPs 概念
- Python - 類 & 物件
- Python - 類屬性
- Python - 類方法
- Python - 靜態方法
- Python - 建構函式
- Python - 訪問修飾符
- Python - 繼承
- Python - 多型
- Python - 方法重寫
- Python - 方法過載
- Python - 動態繫結
- Python - 動態型別
- Python - 抽象
- Python - 封裝
- Python - 介面
- Python - 包
- Python - 內部類
- Python - 匿名類和物件
- Python - 單例類
- Python - 包裝器類
- Python - 列舉
- Python - 反射
- Python 錯誤 & 異常
- Python - 語法錯誤
- Python - 異常
- Python - try-except 塊
- Python - try-finally 塊
- Python - 丟擲異常
- Python - 異常鏈
- Python - 巢狀 try 塊
- Python - 使用者自定義異常
- Python - 日誌記錄
- Python - 斷言
- Python - 內建異常
- Python 多執行緒
- Python - 多執行緒
- Python - 執行緒生命週期
- Python - 建立執行緒
- Python - 啟動執行緒
- Python - 執行緒連線
- Python - 執行緒命名
- Python - 執行緒排程
- Python - 執行緒池
- Python - 主執行緒
- Python - 執行緒優先順序
- Python - 守護執行緒
- Python - 執行緒同步
- Python 同步
- Python - 執行緒間通訊
- Python - 執行緒死鎖
- Python - 中斷執行緒
- Python 網路
- Python - 網路
- Python - 套接字程式設計
- Python - URL 處理
- Python - 泛型
- Python 庫
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 其他
- Python - 日期 & 時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI 程式設計
- Python - XML 處理
- Python - GUI 程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 擴充套件
- Python - 工具/實用程式
- Python - GUIs
- Python 高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類進行超程式設計
- Python - 模擬和存根
- Python - 猴子補丁
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python 有用資源
- Python - 問答
- Python - 線上測驗
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 有用資源
- Python - 討論
- Python 編譯器
- NumPy 編譯器
- Matplotlib 編譯器
- SciPy 編譯器
Python - URL 處理
在網際網路世界中,不同的資源由 URL(統一資源定位符)標識。Python 的標準庫包含 **urllib** 包,其中包含用於處理 URL 的模組。它可以幫助您解析 URL、獲取網路內容和管理錯誤。
本教程介紹 urllib 基礎知識,幫助您開始使用它。使用 urllib 提高您使用 Python 進行網路抓取、獲取資料和管理 URL 的技能。
**urllib** 包包含以下用於處理 URL 的模組:
**urllib.parse** 模組用於將 URL 解析成其各個部分。
**urllib.request** 模組包含用於開啟和讀取 URL 的函式。
**urllib.error** 模組包含 urllib.request 丟擲的異常的定義。
**urllib.robotparser** 模組解析 robots.txt 檔案。
urllib.parse 模組
此模組作為標準介面,用於從 URL 字串中獲取各個部分。該模組包含以下函式:
urlparse(urlstring)
將 URL 解析成六個元件,返回一個包含 6 個專案的命名元組。每個元組項都是一個字串,對應以下屬性:
屬性 | 索引 | 值 |
---|---|---|
scheme | 0 | URL 方案說明符 |
netloc | 1 | 網路位置部分 |
path | 2 | 分層路徑 |
params | 3 | 最後一個路徑元素的引數 |
query | 4 | 查詢元件 |
fragment | 5 | 片段識別符號 |
username | 使用者名稱 | |
password | 密碼 | |
hostname | 主機名(小寫) | |
Port | 埠號(整數),如果存在 |
示例
from urllib.parse import urlparse url = "https://example.com/employees/name/?salary>=25000" parsed_url = urlparse(url) print (type(parsed_url)) print ("Scheme:",parsed_url.scheme) print ("netloc:", parsed_url.netloc) print ("path:", parsed_url.path) print ("params:", parsed_url.params) print ("Query string:", parsed_url.query) print ("Frgment:", parsed_url.fragment)
它將產生以下 **輸出**:
<class 'urllib.parse.ParseResult'> Scheme: https netloc: example.com path: /employees/name/ params: Query string: salary>=25000 Frgment:
parse_qs(qs))
此函式解析給定為字串引數的查詢字串。資料以字典的形式返回。字典的鍵是唯一的查詢變數名稱,值是每個名稱的值列表。
要進一步將查詢字串中的查詢引數提取到字典中,請使用 ParseResult 物件的 query 屬性的 parse_qs() 函式,如下所示:
示例
from urllib.parse import urlparse, parse_qs url = "https://example.com/employees?name=Anand&salary=25000" parsed_url = urlparse(url) dct = parse_qs(parsed_url.query) print ("Query parameters:", dct)
它將產生以下 **輸出**:
Query parameters: {'name': ['Anand'], 'salary': ['25000']}
urlsplit(urlstring)
這類似於 urlparse(),但不會從 URL 中拆分 params。如果需要更新的 URL 語法(允許將引數應用於 URL 路徑部分的每個段),則通常應使用此函式而不是 urlparse()。
urlunparse(parts)
此函式與 urlparse() 函式相反。它根據 urlparse() 返回的元組構建 URL。parts 引數可以是任何六項可迭代物件。這將返回一個等效的 URL。
示例
from urllib.parse import urlunparse lst = ['https', 'example.com', '/employees/name/', '', 'salary>=25000', ''] new_url = urlunparse(lst) print ("URL:", new_url)
它將產生以下 **輸出**:
URL: https://example.com/employees/name/?salary>=25000
urlunsplit(parts)
將 urlsplit() 返回的元組的元素組合成一個完整的 URL 字串。parts 引數可以是任何五項可迭代物件。
urllib.request 模組
此模組提供了用於透過使用 **urlopen()** 函式處理 URL 的開啟和讀取操作的函式和類。
urlopen() 函式
此函式開啟給定的 URL,該 URL 可以是字串或 Request 物件。可選的 timeout 引數指定阻塞操作的超時時間(以秒為單位)。這實際上僅適用於 HTTP、HTTPS 和 FTP 連線。
此函式始終返回一個可以作為上下文管理器工作的物件,並且具有 url、headers 和 status 屬性。對於 HTTP 和 HTTPS URL,此函式返回一個略作修改的 http.client.HTTPResponse 物件。
示例
以下程式碼使用 urlopen() 函式從影像檔案讀取二進位制資料,並將其寫入本地檔案。您可以使用任何影像檢視器在您的計算機上開啟影像檔案。
from urllib.request import urlopen obj = urlopen("https://tutorialspoint.tw/images/logo.png") data = obj.read() img = open("img.jpg", "wb") img.write(data) img.close()
它將產生以下 **輸出**:

Request 物件
urllib.request 模組包含 Request 類。此類是 URL 請求的抽象。建構函式需要一個必需的字串引數,即有效的 URL。
語法
urllib.request.Request(url, data, headers, origin_req_host, method=None)
引數
**url** - 一個有效的 URL 字串
**data** - 指定要傳送到伺服器的其他資料的物件。此引數只能與 HTTP 請求一起使用。資料可以是位元組、類檔案物件和位元組類物件的迭代器。
**headers** - 應該是標頭及其關聯值的字典。
**origin_req_host** - 應該是原始事務的請求主機
**method** - 應該是指示 HTTP 請求方法的字串。GET、POST、PUT、DELETE 和其他 HTTP 動詞之一。預設為 GET。
示例
from urllib.request import Request obj = Request("https://tutorialspoint.tw/")
此 Request 物件現在可以用作 urlopen() 方法的引數。
from urllib.request import Request, urlopen obj = Request("https://tutorialspoint.tw/") resp = urlopen(obj)
urlopen() 函式返回一個 HttpResponse 物件。呼叫其 read() 方法將獲取給定 URL 上的資源。
from urllib.request import Request, urlopen obj = Request("https://tutorialspoint.tw/") resp = urlopen(obj) data = resp.read() print (data)
傳送資料
如果將 data 引數定義為 Request 建構函式,則會將 POST 請求傳送到伺服器。資料應為以位元組表示的任何物件。
from urllib.request import Request, urlopen from urllib.parse import urlencode values = {'name': 'Madhu', 'location': 'India', 'language': 'Hindi' } data = urlencode(values).encode('utf-8') obj = Request("https://example.com", data)
傳送標頭
Request 建構函式還接受 header 引數,以將標頭資訊推送到請求中。它應該是一個字典物件。
headers = {'User-Agent': user_agent} obj = Request("https://example.com", data, headers)
urllib.error 模組
urllib.error 模組中定義了以下異常:
URLError
由於沒有網路連線(沒有到指定伺服器的路由)或指定的伺服器不存在而引發 URLError。在這種情況下,引發的異常將具有 'reason' 屬性。
示例
from urllib.request import Request, urlopen import urllib.error as err obj = Request("http://www.nosuchserver.com") try: urlopen(obj) except err.URLError as e: print(e)
它將產生以下 **輸出**:
HTTP Error 403: Forbidden
HTTPError
每次伺服器傳送 HTTP 響應時,它都與一個數字“狀態程式碼”相關聯。程式碼指示伺服器為何無法滿足請求。預設處理程式將為您處理其中一些響應。對於它無法處理的響應,urlopen() 函式將引發 HTTPError。HTTPErrors 的典型示例是“404”(頁面未找到),“403”(請求被禁止)和“401”(需要身份驗證)。
示例
from urllib.request import Request, urlopen import urllib.error as err obj = Request("https://python.club.tw/fish.html") try: urlopen(obj) except err.HTTPError as e: print(e.code)
它將產生以下 **輸出**:
404