#!/usr/bin/evn python
import re #導入正規表達式子產品
import urllib #導入urllib子產品,讀取頁面與下載下傳頁面需要用到
def getHtml(url): #定義getHtml()函數,用來擷取頁面源代碼
page = urllib.urlopen(url) #urlopen()根據url來擷取頁面源代碼
html = page.read() #從擷取的對象中讀取内容
return html
def getImage(html): #定義getImage()函數,用來擷取圖檔位址并下載下傳
reg = r'src="(.*?.jpg)" width' #定義比對圖檔位址的url的正規表達式
imgre = re.compile(reg) #對正規表達式進行編譯,運作效率更高
imagelist = imgre.findall(html) #使用findall()查找html中比對正規表達式的圖檔url
x = 0
for imageurl in imagelist:
urllib.urlretrieve(imageurl,'picture_%s.jpg' % x) #urlretrieve()下載下傳檔案
x +=1
uri = raw_input("請輸入網址: ")
r = r'^http://'
if re.match(r,uri):
html2 = getHtml(uri)
else:
html2 = getHtml("http://" + uri)
getImage(html2)
運作腳本test.py
本文轉自 技術花妞妞 51CTO部落格,原文連結:http://blog.51cto.com/xiaogongju/2061744