(參考資料:現代魔法學院 http://www.nowamagic.net/academy/detail/1302803)html
Python標準庫中有許多實用的工具類,可是在具體使用時,標準庫文檔上對使用細節描述的並不清楚,好比 urllib和urllib2 這個 HTTP 客戶端庫。這裏總結了一些 urllib和urlib2 庫的使用細節。正則表達式
Python urllib 庫提供了一個從指定的 URL 地址獲取網頁數據,而後對其進行分析處理,獲取想要的數據。服務器
1、urllib經常使用函數介紹:網絡
1. urlopen()函數:即建立一個類文件對象爲指定的 url 來讀取。函數
能夠使用help(urllib.urlopen)查看函數說明。工具
urlopen(url, data=None, proxies=None)
Create a file-like object for the specified URL to read from.post
urlopen返回一個類文件對象,它提供了以下方法:url
read(),readline,readlines,fileno和close: 這些方法的使用和文件對象同樣;spa
info(): 返回一個httplib.HTTPMessage對象,表示遠程服務器返回的頭信息。.net
getcode():返回Http狀態碼,若是是http請求,200表示請求成功完成,404表示網址沒有找到。
getutl: 返回請求的url地址。
示例:
>>>import urllib
>>>baidu = urllib.urlopen('http://www.baidu.com')
>>>baidu.read()
>>> print baidu.info()
輸出:
Date: Fri, 24 Apr 2015 05:41:40 GMT
Server: Apache
Cache-Control: max-age=86400
Expires: Sat, 25 Apr 2015 05:41:40 GMT
Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT
ETag: "51-4b4c7d90"
Accept-Ranges: bytes
Content-Length: 81
Connection: Close
Content-Type: text/html
>>>for line in baidu: #等價於read(),就像在操做本地文件,將網頁數據打印出來。
print line,
baidu.close()
補充:
urllib.urlopen('http://www.baidu.com')
urllib.urlopen('ftp://192.168.1.200')
urllib.urlopen('file:nowangic.py')
urllib.urlopen('file:F:\test\helloworld.py')
2. urlretrieve()函數:直接將遠程數據下載到本地。
能夠使用help(urllib.urlretvieve)查看函數說明
Help on function urlretrieve in module urllib:
urlretrieve(url, filename=None, reporthook=None, data=None)
示例1:
>>>urllib.urlretrieve('http://www.soso.com','c://soso.html')
('c://soso.html', <httplib.HTTPMessage instance at 0x0000000005187A48>)
示例2:下面是urlretrieve()下載文件實例,能夠顯示下載進度。
#coding:utf-8
import urllib
def cbk(a,b,c):
"""
@a: 已經下載的數據塊
@b: 數據塊的大小
@c: 遠程文件的大小
"""
per = 100.0 *a*b/c
if per >100:
per = 100
print '#%d%%'% per
url = 'http://www.soso.com'
local = 'c://test//soso.html'
urllib.urlretrieve(url,local,cbk)
示例3:爬蟲練習:
#-*-coding:utf-8-*-
""" 爬蟲練習
Date:06-15-2015
"""
import urllib
import re
#獲取指定url網頁內容
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
#利用正則表達式將指定的圖片下載
def getImg(html):
reg = 'src="(.*?\.jpg)" pic_ext'
regimg = re.compile(reg)
imglist = re.findall(regimg,html)
x = 0
for img in imglist:
urllib.urlretrieve(img,'%s.jpg' % x)
x+=1
Html = getHtml('http://tieba.baidu.com/p/3825178610')
Img = getImg(Html)