以下是源碼,參考的是蟲師寫的簡單爬蟲的實現,蟲師教程太老,導致範例跑不起來。 原因是裏面的網址404了。必須要正則能夠搜索到圖片。
本文範例所用網址裏面的圖片命名是 http://tb.himg.baidu.com/sys/portrait/item/33a5786c3936343937303734355a33
#-*- coding:utf-8 -*- import re import urllib def getHtml(url): page = urllib.urlopen(url) html = page.read() return html def getImg(html): reg = r'src="(http://.*?)"' imgre = re.compile(reg) imglist = re.findall(imgre,html) x = 0 for imgurl in imglist: print x urllib.urlretrieve(imgurl,'%s.jpg' % x) x+=1 print x return imglist html = getHtml("http://tieba.baidu.com/p/4817501655") getImg(html)
運行以上代碼 就會把網址裏的所有jpg圖片下載到本地目錄也就是和程序文件同目錄下