上一篇博文中提到用正則表達式來匹配數據項,可是寫起來容易出錯,若是有過DOM開發經驗或者使用過jQuery的朋友看到BeautifulSoup就像是見到了老朋友同樣。html
Mac安裝BeautifulSoup很簡單,打開終端,執行如下語句,而後輸入密碼便可安裝web
sudo easy_install beautifulsoup4
複製代碼
# coding=utf-8
import urllib
from bs4 import BeautifulSoup
# 定義個函數 抓取網頁內容
def getHtml(url):
webPage = urllib.urlopen(url)
html = webPage.read()
return html
# 定義一個函數 抓取網頁中的圖片
def getNewsImgs(html):
# 建立BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
# 查找全部的img標籤
urlList = soup.find_all("img")
length = len(urlList)
# 遍歷標籤 下載圖片
for i in range(length):
imgUrl = urlList[i].attrs["src"]
urllib.urlretrieve("http://www.abc.edu.cn/news/"+imgUrl,'news-%s.jpg' % i)
# 獲取網頁
html = getHtml("http://www.abc.edu.cn/news/show.aspx?id=21430&cid=5")
# 抓取圖片
getNewsImgs(html)
複製代碼