Python urllib和urllib2模塊學習(一)

(參考資料:現代魔法學院 http://www.nowamagic.net/academy/detail/1302803html

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.open的參數有特別要示,要遵循一些網絡協議,好比http,ftp,也就是說在網址的開頭必需要有http://或ftp://如:

  urllib.urlopen('http://www.baidu.com')

  urllib.urlopen('ftp://192.168.1.200')

  • 若要使用本地文件,就須要在前面加filt關鍵字,如:

  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)

  • 參數 finename 指定了保存本地路徑(若是參數未指定,urllib會生成一個臨時文件保存數據。)
  • 參數 reporthook 是一個回調函數,當鏈接上服務器、以及相應的數據塊傳輸完畢時會觸發該回調,咱們能夠利用這個回調函數來顯示當前的下載進度。
  • 參數 data 指 post 到服務器的數據,該方法返回一個包含兩個元素的(filename, headers)元組,filename 表示保存到本地的路徑,header 表示服務器的響應頭。

 示例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)

相關文章
相關標籤/搜索