利用python抓取網絡圖檔的步驟是:
1、根據給定的網址擷取網頁源代碼
2、利用正規表達式把源代碼中的圖檔位址過濾出來
3、根據過濾出來的圖檔位址下載下傳網絡圖檔
以下是比較簡單的一個抓取某一個百度貼吧網頁的圖檔的實作:
# -*- coding: utf-8 -*-
# feimengjuan
import re
import urllib
import urllib2
#抓取網頁圖檔
#根據給定的網址來擷取網頁詳細資訊,得到的html就是網頁的源代碼
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def getImg(html):
#利用正規表達式把源代碼中的圖檔位址過濾出來
reg = r'src="(.+?\.jpg)" pic_ext'
imgre = re.compile(reg)
imglist = imgre.findall(html) #表示在整個網頁中過濾出所有圖檔的位址,放在imglist中
x = 0
for imgurl in imglist:
urllib.urlretrieve(imgurl,'%s.jpg' %x) #打開imglist中儲存的圖檔網址,并下載下傳圖檔儲存在本地
x = x + 1
html = getHtml("http://tieba.baidu.com/p/2460150866")#擷取該網址網頁詳細資訊,得到的html就是網頁的源代碼
getImg(html)#從網頁源代碼中分析并下載下傳儲存圖檔
進一步對代碼進行了整理,在本地建立了一個“圖檔”檔案夾來儲存圖檔
# -*- coding: utf-8 -*-
# feimengjuan
import re
import urllib
import urllib2
import os
#抓取網頁圖檔
#根據給定的網址來擷取網頁詳細資訊,得到的html就是網頁的源代碼
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
#建立儲存圖檔的檔案夾
def mkdir(path):
path = path.strip()
# 判斷路徑是否存在
# 存在 True
# 不存在 Flase
isExists = os.path.exists(path)
if not isExists:
print u'建立了名字叫做',path,u'的檔案夾'
# 建立目錄操作函數
os.makedirs(path)
return True
else:
# 如果目錄存在則不建立,并提示目錄已經存在
print u'名為',path,u'的檔案夾已經建立成功'
return False
# 輸入檔案名,儲存多張圖檔
def saveImages(imglist,name):
number = 1
for imageURL in imglist:
splitPath = imageURL.split('.')
fTail = splitPath.pop()
if len(fTail) > 3:
fTail = 'jpg'
fileName = name + "/" + str(number) + "." + fTail
# 對于每張圖檔位址,進行儲存
try:
u = urllib2.urlopen(imageURL)
data = u.read()
f = open(fileName,'wb+')
f.write(data)
print u'正在儲存的一張圖檔為',fileName
f.close()
except urllib2.URLError as e:
print (e.reason)
number += 1
#擷取網頁中所有圖檔的位址
def getAllImg(html):
#利用正規表達式把源代碼中的圖檔位址過濾出來
reg = r'src="(.+?\.jpg)" pic_ext'
imgre = re.compile(reg)
imglist = imgre.findall(html) #表示在整個網頁中過濾出所有圖檔的位址,放在imglist中
return imglist
#建立本地儲存檔案夾,并下載下傳儲存圖檔
if __name__ == '__main__':
html = getHtml("http://tieba.baidu.com/p/2460150866")#擷取該網址網頁詳細資訊,得到的html就是網頁的源代碼
path = u'圖檔'
mkdir(path) #建立本地檔案夾
imglist = getAllImg(html) #擷取圖檔的位址清單
saveImages(imglist,path) # 儲存圖檔
結果在“圖檔”檔案夾下儲存了幾十張圖檔,如截圖:
總結
以上就是本文關于Python實作簡單網頁圖檔抓取完整代碼執行個體的全部内容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站:
Python爬蟲執行個體爬取網站搞笑段子
python爬蟲系列Selenium定向爬取虎撲籃球圖檔詳解
如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!
本文标題: Python實作簡單網頁圖檔抓取完整代碼執行個體
本文位址: http://www.cppcns.com/jiaoben/python/214901.html