Python爬蟲,一般用于抓取特定的內容,最近想學學,通過網絡抓取自己想要的內容,于是乎學習了一下Python,用一個小案例來紀念一下學習的成果。
案例程序主要功能:抓取我們學校校園網新聞中的圖片
#coding=utf-8
import urllib
import re
# 定義個函數 抓取網頁內容
def getHtml(url):
webPage = urllib.urlopen(url)
html = webPage.read()
return html
# 定義一個函數 抓取網頁中的圖片
def getNewsImgs(html):
# 正則表達式
reg = r'src="(.+?\.jpg)"'
img = re.compile(reg)
# 獲取網頁中所有符合條件的圖片url
imglist = re.findall(img,html)
x = 0
# 根據圖片地址下載圖片并重命名
for imgUrl in imglist:
urllib.urlretrieve("http://www.abc.edu.cn/news/"+imgUrl,'news-%s.jpg' % x)
x += 1
# 獲取網頁
html = getHtml("http://www.abc.edu.cn/news/show.aspx?id=21413&cid=5")
# 抓取圖片
print getNewsImgs(html)
效果:成功抓取了新聞中的兩張圖片O(∩_∩)O~
爬蟲抓圖片.gif