上一篇博文中提到用正則表達式來匹配數(shù)據(jù)項,但是寫起來容易出錯放椰,如果有過DOM開發(fā)經(jīng)驗或者使用過jQuery的朋友看到BeautifulSoup就像是見到了老朋友一樣。
安裝BeautifulSoup
Mac安裝BeautifulSoup很簡單拿撩,打開終端如蚜,執(zhí)行以下語句头滔,然后輸入密碼即可安裝
sudo easy_install beautifulsoup4
改代碼
#coding=utf-8
import urllib
from bs4 import BeautifulSoup
# 定義個函數(shù) 抓取網(wǎng)頁內(nèi)容
def getHtml(url):
webPage = urllib.urlopen(url)
html = webPage.read()
return html
# 定義一個函數(shù) 抓取網(wǎng)頁中的圖片
def getNewsImgs(html):
# 創(chuàng)建BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
# 查找所有的img標(biāo)簽
urlList = soup.find_all("img")
length = len(urlList)
# 遍歷標(biāo)簽 下載圖片
for i in range(length):
imgUrl = urlList[i].attrs["src"]
urllib.urlretrieve("http://www.abc.edu.cn/news/"+imgUrl,'news-%s.jpg' % i)
# 獲取網(wǎng)頁
html = getHtml("http://www.abc.edu.cn/news/show.aspx?id=21430&cid=5")
# 抓取圖片
getNewsImgs(html)
效果:換了一個新聞坤检,抓取了新聞中的三張圖片O(∩_∩)O~
爬蟲抓圖片.gif