1. 程式人生 > >爬蟲中網頁分析的幾種技術

爬蟲中網頁分析的幾種技術

一般來說我們只抓取網頁中的特定資料,比如抓取某人所有的blog,我們就只關心list 頁面中文章列表那部分的連結和title

有幾種技術可以用來分析網頁

1)正則匹配

2)一般字串匹配content.substring(pattern, startIndex),一般是帶有startIndex的substring,而不是每次都是從頭匹配

3) 基於sax的事件

4)DOM + XPath

抓去的資料有兩種

1)基於資料本身的parttern,比如連結、email adrress,適合用正則

2)基於位置。資料本身沒什麼特別,關鍵在於在什麼位置出現。適合用其他3種,

基於sax事件的最好,流式處理,不需要儲存整個網頁,缺點是有些網頁不規範,sax 要求必須是合法、well formed xml。

substring和正則一般需要先把網頁讀成字串,substring更簡單輕量級一些,

DOM+xpath太殺雞用牛刀了

例子,把自己csdn上所有的博文扒下來:

from urllib2 import Request, urlopen, URLError

page, articleList, visited, startOver = 1, [], set(), False
while not startOver:
    req = Request('http://blog.csdn.net/binling/article/list/' + str(page), headers={'User-agent': 'Mozilla 5.10'})
    try:content = urlopen(req).read()
    except URLError, e: break
    pos = 0
    while True:
        try:
            pos = content.index('link_title', pos)
            pos = content.index('href', pos)
            pos = content.index('"', pos)
            end = content.index('"', pos + 1)
            link = content[pos + 1:end].strip().decode('utf-8')
            if link in visited:
                startOver = True
                break
            pos = content.index('>', end)
            end = content.index('</a>', pos)
            title = content[pos + 1: end].strip()
            articleList.append((title.decode('utf-8'), link))
            visited.add(link)
        except: break
    page += 1

home = 'C:\\Personal\\CSDN'
for title, link in articleList:
    for c in '/\*:<>?"|':
        if c in title: title = title.replace(c, ' ')
    content = urlopen(Request('http://blog.csdn.net' + link, headers={'User-agent': 'Mozilla 5.10'})).read()
    with open(home + '\\' + title + '.html', 'w') as f:
        f.write(content)
        print title