利用python抓取網絡圖片的步驟是:
1、根據給定的網址獲取網頁源代碼
2、利用正則表達式把源代碼中的圖片地址過濾出來
3、根據過濾出來的圖片地址下載網絡圖片
以下是比較簡單的一個抓取某一個百度貼吧網頁的圖片的實現:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# -*- 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) #從網頁源代碼中分析并下載保存圖片 |
進一步對代碼進行了整理,在本地創建了一個“圖片”文件夾來保存圖片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
# -*- 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實現簡單網頁圖片抓取完整代碼實例的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/feimengjuan/article/details/51163803