urllib包和http包都是面向HTTP協議的。其中urllib主要用于處理 URL,使用urllib操作URL可以像使用和打開本地文件一樣地操作。而 http包則實現了對 HTTP協議的封裝,是urllib.request模塊的底層。
1.urllib包簡介
2. http 包簡介
1.urllib包簡介
urllib包主要模塊有:
1.urllib.request -----用于打開 URL網址;
2.urllib.error ---------定義了常見的urllib.request會引發的異常;
3.urllib.parse---------用于解析 URL;
具體方法:
urllib.request.urlopen( url,data,proxies ) :用于打開 url
參數如下:
url:要進行操作的 URL地址
data:可選項。向URL 傳遞的數據。
proxies:可選項。使用的代理地址
import urllib.requesturl = 'http://www.baidu.com' #網頁為百度首頁respone = urllib.request.urlopen(url) #打開url地址,并返回一個 HTTPRespone實例html = respone.read().decode('utf-8') #調用實例的 read()方法,并用 utf-8進行解碼處理。就得出完整的百度的HTML文件print(html) 部分打印結果:
<html><head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta content="always" name="referrer"> <meta name="theme-color" content="#2932e1"> <link rel="shortcut icon" href="/favicon.ico" rel="external nofollow" type="image/x-icon" /> <link rel="search" type="application/opensearchdescription+xml" href="/content-search.xml" rel="external nofollow" title="百度搜索" /> <link rel="icon" sizes="any" mask rel="external nofollow" >
urllib.request.urlretrieve(url,filename,reporthook,data) :用于將 URL的HTML文件下載并保存為本地文件
參數如下:
url:要下載的網頁
filename:保存在主機的路徑,可選項。
reporthook:一個回調函數,可選項。
data:發送的數據,一般用于 post,可選項。
特別:關于urlretrieve()的回調函數reporthook:可以用來顯示下載的進度,幾乎已經封裝好
import urllib.requestdef callbackfunc(blocknum, blocksize, totalsize): #這三個參數是由 urlretrieve自動賦值的 '''回調函數 @blocknum: 已經下載的數據塊 @blocksize: 數據塊的大小 @totalsize: 遠程文件的大小 ''' percent = 100.0 * blocknum * blocksize / totalsize if percent > 100: percent = 100 print( "%.2f%%"% percent) #保留兩位小數url = 'http://www.sina.com'local = 'd://sina.html' #下載的html文件保存在 d盤的sina.html里urllib.request.urlretrieve(url,local,callbackfunc) #沒下載完一個數據塊,就會執行回調函數一次
執行結果:
//只顯示局部 0.00% 1.38% 2.76% 4.13% 5.51% 6.89%
新聞熱點
疑難解答