python實現簡單圖片爬蟲並保存
阿新 • • 發佈:2017-06-28
.com 貪婪模式 web頁面 logs urn 並不是 python 保存 light
先po代碼
#coding=utf-8 import urllib.request #3之前的版本直接用urllib即可,下同 #該模塊提供了web頁面讀取數據的接口,使得我們可以像讀取本地文件一樣讀取www或者ftp上的數據 import re import os def getHtml(url): page = urllib.request.urlopen(url); html = page.read(); return html; def getImg(html): imglist = re.findall(‘img src="(http.*?)"‘,html)#1 #http.*?表示非貪婪模式的匹配,只要符合http就匹配完成,不再看後面的內容是否匹配,即在能使整個匹配成功的前提下,使用最少的重復 return imglist html = getHtml("https://www.zhihu.com/question/39731953").decode("utf-8"); imagesUrl = getImg(html); if os.path.exists("D:/imags") == False: os.mkdir("D:/imags"); count = 0; #文件的起始名稱為 0 for url in imagesUrl: print(url) if(url.find(‘.‘) != -1):#2 name = url[url.find(‘.‘,len(url) - 5):]; bytes = urllib.request.urlopen(url); f = open("D:/imags/"+str(count)+name, ‘wb‘); #代開一個文件,準備以二進制寫入文件 f.write(bytes.read());#write並不是直接將數據寫入文件,而是先寫入內存中特定的緩沖區 f.flush();#將緩沖區的數據立即寫入緩沖區,並清空緩沖區 f.close();#關閉文件 count+=1;
代碼分析:
1.re.findall語法: findall(parttern,string,flags=0)
含義:返回string中與partten匹配的全部字符串,返回形式是數組
2.find()語法:find(str,pos_start,pos_end)
含義:在url中查找str字符串的位置,pos_start是指從哪一個位置開始找,默認值為0,查找的默認位置,默認值為-1,若在url中找不到str,則返回-1
python實現簡單圖片爬蟲並保存