# coding=<encoding name> 例如,可添加# coding=utf-8 import urllib import re # 定義一個方法,把整個頁面下載下來 def getHtml(url): page = urllib.urlopen(url) # 打開網頁 html = page.read() #讀取 URL上面的數據 return html # 返回內容 # 再定義一個方法,篩選頁面中想要的元素,通過正則表達式的匹配 def getimage(html): reg = r'src="(.+?\.jpg)" pic_ext' # 定義一個正則表達式 # re.compile() 把正則表達式編譯成一個正則表達式對象 imagere =re.compile(reg) # re.findall() 方法讀取html 中包含 imgre(正則表達式)的數據。 imagerelist = re.findall(imagere,html) # 遍歷圖片 x = 0 for imageurl in imagerelist: # 這里的核心是用到了urllib.urlretrieve(),方法,直接將遠程數據下載到本地 urllib.urlretrieve(imageurl,'%s.jpg'% x) x= x+1 # 調用getHtml 傳入一個網址 ht = getHtml("http://tieba.baidu.com/p/2460150866") # 調用getimage ,拿到圖片 print getimage(ht)
運行的效果