Python簡單的爬蟲

Python簡單的爬蟲


最簡單的爬蟲

# -*- coding : utf-8 -*-
import urllib

url = 'http://www.baidu.com'

html = urllib.urlopen(url)

print html.read()

也可以打印出網頁的其他信息

#獲取狀態碼
print html.getcode()

#獲取傳入的參數
print html.geturl()

#獲取網頁的head信息
print html.info()

編碼問題

# -*- coding : utf-8 -*-
import urllib

url = 'http://www.163.com/'

html = urllib.urlopen(url)

#轉換成我們想要的編碼
print html.read().decode('gbk').encode('utf-8')

# 如果編碼不統一,一個網頁包含多個編碼,可能會有一些字符無法正常被轉換,可能報錯
# 可以使用一下方法

print html.read().decode('gbk','ignore').encode('utf-8')

帶進度條的爬蟲

# -*- coding : utf-8 -*-
'''
帶進度條的爬蟲
'''

import urllib

'''
  顯示下載進度,可以是文件或者網頁
  參數說明 1)網址 2)本地的網頁保存路徑+文件名 3) 一個函數調用,這個函數
  必須要有三個參數
  1.到目前爲止傳遞的數據塊數量
  2.每個數據塊的大小,單位是byte,字節
  3.遠程文件的大小
'''

def callback(receivedData,weight,dataSize):  
    '''
    receivedData 已經接收的文件的大小
    weight 每個文件 的大小
    dataSize 目標文件的大小
    '''
    downloadProcess = 100.0 * receivedData * weight / dataSize
    if downloadProcess > 100:
        downloadProcess = 100
    print '%.2f%%' % downloadProcess    

url = 'http://www.163.com'

local = 'D:\\pythonfile\\html.html'

urllib.urlretrieve(url,local,callback)
發佈了266 篇原創文章 · 獲贊 9 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章