先po代碼html
#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;
代碼分析:python
1.re.findall語法: findall(parttern,string,flags=0)web
含義:返回string中與partten匹配的所有字符串,返回形式是數組數組
2.find()語法:find(str,pos_start,pos_end)url
含義:在url中查找str字符串的位置,pos_start是指從哪個位置開始找,默認值爲0,查找的默認位置,默認值爲-1,若在url中找不到str,則返回-1code