Python 提供了非常強大的正則表達式,我們需要先要了解一點python 正則表達式的知識才行。
http://www.cnblogs.com/fnng/archive/2013/05/20/3089816.html
假如我們百度貼吧找到了幾張漂亮的壁紙,通過到前段查看工具。找到了圖片的地址,如:src=”http://imgsrc.baidu.com/forum......jpg”pic_ext=”jpeg”
我們又創建了getImg()函數,用于在獲取的整個頁面中篩選需要的圖片連接。re模塊主要包含了正則表達式:
re.compile() 可以把正則表達式編譯成一個正則表達式對象.
re.findall() 方法讀取html 中包含 imgre(正則表達式)的數據。
運行腳本將得到整個頁面中包含圖片的URL地址
把篩選的圖片地址通過for循環遍歷并保存到本地,代碼如下:
#coding=utf-8
import urllib.request
import re
def getHtml(url):
? ? page = urllib.request.urlopen(url)? ?
html = page.read()? ?
return htmldef
getImg(html):?
? reg = r'src="(.+?\.jpg)" pic_ext'? ?
imgre = re.compile(reg)?
? html = html.decode('utf-8');?
? imglist = re.findall(imgre,html)? ?
? ?x = 0?
? for imgurl in imglist:? ?
? ? urllib.request.urlretrieve(imgurl,'%s.jpg' % x)? ? ?
? x+=1?
? return html
html = getHtml("http://tieba.baidu.com/p/2460150866");
print (getImg(html));