歡迎您光臨本站 註冊首頁

Python urllib.request對象案例解析

←手機掃碼閱讀     qp18502452 @ 2020-05-12 , reply:0

什麼是 Urllib 庫?
urllib 庫 是 Python 內置的 HTTP 請求庫。urllib 模塊提供的上層接口,使訪問 www 和 ftp 上的數據就像訪問本地文件一樣。
有以下幾種模塊:
1.urllib.request 請求模塊
2. urllib.error 異常處理模塊
3. urllib.parse url 解析模塊
4. urllib.robotparser robots.txt 解析模塊
Urllib 庫下的幾種模塊基本使用如下:
urllib.request
關於 urllib.request: urllib.request 模塊提供了最基本的構造 HTTP (或其他協議如 FTP)請求的方法,利用它可以模擬瀏覽器的一個請求發起過程。利用不同的協議去獲取 URL 信息。它的某些接口能夠處理基礎認證 ( Basic Authenticaton) 、redirections (HTTP 重定向)、 Cookies (瀏覽器 Cookies)等情況。而這些接口是由 handlers 和 openers 對象提供的。
1.常用的方法有
read()==讀取文件內容
geturl()==獲取請求url
getheaders()==獲取http請求頭信息
getcode()==獲取狀態碼
readlines()==獲取一行
2.案例
#coding=utf-8 #import urllib.request #=========response方法使用 #read()==讀取文件內容 #geturl()==獲取請求url #getheaders()==獲取http請求頭信息 #getcode()==獲取狀態碼 #readlines()==獲取一行 #url="http://www.baidu.com"; #response = urllib.request.urlopen(url); #=====案例1 # str = response.read().decode();#這樣通過decode轉換為utf8 # with open("baidu.html","w",encoding="utf8") as fp: # fp.write(str); #=====案例2通過字節流寫=默認通過read讀取的是字節流 # with open("bai.html","wb") as fp: # fp.write(response.read()); #==使用字節流讀取存圖片 # image_url='https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3772530225,1800402028&fm=26&gp=0.jpg'; # response = urllib.request.urlopen(image_url); # with open("mv.jpg",'wb') as fp: # fp.write(response.read()); #案例3==使用內置函數讀取圖片 #image_url='https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3772530225,1800402028&fm=26&gp=0.jpg'; #urllib.request.urlretrieve(image_url,"chun.jpg");


[qp18502452 ] Python urllib.request對象案例解析已經有247次圍觀

http://coctec.com/docs/python/shhow-post-234035.html