執行個體詳解Python實現簡單網頁圖片抓取

來源:互聯網
上載者:User
本文主要介紹了Python實現簡單網頁圖片抓取完整代碼執行個體,具有一定借鑒價值,需要的朋友可以參考下。

利用python抓取網狀圖片的步驟是:
1、根據給定的網址擷取網頁原始碼
2、利用Regex把原始碼中的圖片地址過濾出來
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):   #利用Regex把原始碼中的圖片地址過濾出來   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):   #利用Regex把原始碼中的圖片地址過濾出來   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) # 儲存圖片

結果在“圖片”檔案夾下儲存了幾十張圖片,如:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.