python爬蟲學習小程序

#coding:utf-8
#-------------------------------------------------------------------------------
# Name:        模塊1
# Purpose:
#
# Author:      mrwang
#
# Created:     18/04/2014
# Copyright:   (c) mrwang 2014
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import urllib
def main():
    url = 'http://xxxxxxx.xx'
    html = urllib.urlopen(url)
    # print html.read() #讀取內容
    # print html.read().decode('gbk').encode('utf-8') #亂碼解決
    # print html.read().decode('gbk', 'ignore').encode('utf-8') #一個頁面多個編碼 加ignore 忽略無法顯示的字符
    # print html.info() #查看網頁頭部信息
    '''
    Connection: close
    Date: Fri, 18 Apr 2014 03:13:46 GMT
    Server: Microsoft-IIS/6.0
    MicrosoftOfficeWebServer: 5.0_Pub
    pragma: no-cache
    cache-control: private
    Content-Length: 50853
    Content-Type: text/html
    Expires: Thu, 17 Apr 2014 03:13:44 GMT
    Set-Cookie: web%5Fid=9952508807; path=/
    Set-Cookie: ASPSESSIONIDQCTQRBQA=NJFIJEBAIFPPLGFKELICDDEL; path=/
    Cache-control: no-cache
    '''
    # print html.getcode() #返回訪問狀態碼
    # print html.geturl() #返回網頁
    # urllib.urlretrieve(url, "c:\\abc.txt") #下載網頁
    # html.close() #關閉連接
    '''
    urllib.urlretrieve 方法使用
    1 傳入網址
    2 傳入本地保存路徑文件名
    3 一個函數調用,我們可以任意定義這個函數,但是這個函數一定要有三個參數
        參數1 到目前爲止傳遞的數據塊數量
        參數2 每個數據塊的大小,單位byte,字節
        參數3 獲取的文件的大小 有時候會返回-1
    '''
    urllib.urlretrieve(url, 'C://a.html', callback)
def callback(a, b, c):
    '''
    @參數a 到目前爲止傳遞的數據塊數量
    @參數b 每個數據塊的大小,單位byte,字節
    @參數c 獲取的文件的大小 有時候會返回-1
    '''
    down_progress = 100.0 * a * b / c
    if down_progress > 100:
        down_progress = 100
    print "%.2f%%" % down_progress, #後面加上 , 就不會換行
    '''
    0.00% 16.11% 32.22% 48.33% 64.44% 80.55% 96.66% 100.00%
    '''
if __name__ == '__main__':
    main()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章