爬蟲小技巧(1):約束和常用手段

約束

Python、 Java、 PHP、 C#、 Go 等語言都可以實現(xiàn)爬蟲,但是在爬取網(wǎng)站信息時也需要注意一些約束規(guī)范。國內(nèi)外關(guān)于網(wǎng)絡(luò)數(shù)據(jù)采集相關(guān)的法律法規(guī)在不斷完善中,提倡嚴(yán)格控制網(wǎng)絡(luò)數(shù)據(jù)采集的速度,降低被采集網(wǎng)站服務(wù)器的負(fù)擔(dān)。

爬取一個網(wǎng)站有三種常用的方法,下面分別舉例介紹,所用的是Python2.7,以后更新文章的時候兩種版本都可能出現(xiàn),學(xué)習(xí)還是需要有所輸出的,好記性不如爛筆頭,把這些零散的筆記展現(xiàn)出來也算是一個總結(jié)和實踐了。

注:這里是早期看爬蟲書籍時候?qū)W習(xí)筆記,用的是pyhthon 2.7,升級到3.5版本以后2.X中的urllib2庫發(fā)生了一些變化,變成了urllib庫并被劃分為一些子庫。

1. 爬取網(wǎng)站地圖

def crawl_sitemap(url):
    # 1. 網(wǎng)站地圖爬蟲
    # 使用示例網(wǎng)站robots.txt文件中發(fā)現(xiàn)的網(wǎng)站地圖來下載所有網(wǎng)頁。為解析網(wǎng)站地圖,會使用一個簡單的正則表達(dá)式,
    # 從<loc>標(biāo)簽中提取出URL(更加robust的方法是CSS selector)
    # download the sitemap file

    sitemap = download(url)
    # extract the sitemap links
    links = re.findall('<loc>(.*?)</loc>', sitemap)
    # download each link
    for link in links:
        html = download(link)
        # scrape html here
        # ...
crawl_sitemap(url_sitemap)

2. 遍歷每個網(wǎng)頁的數(shù)據(jù)庫ID

設(shè)置用戶代理:

# 利用網(wǎng)站結(jié)構(gòu)的弱點,更加輕松訪問所有內(nèi)容。
# 下面是一些示例國家的URL,可以看出這些URL只是在結(jié)尾處有區(qū)別,包括國家名和ID
# 一般情況下web服務(wù)器會忽略這個字符串,只使用ID來匹配數(shù)據(jù)庫中的相關(guān)記錄,網(wǎng)頁依然可以加載成功。
# http://example.webscraping.com/view/Afghanistan-1
# http://example.webscraping.com/view/Australia-2
# http://example.webscraping.com/view/Brazil-3

# 下面是使用了該技巧的代碼
# itertools.count(start, step)
# 起始參數(shù)(start)默認(rèn)值為0
# 步長(step)默認(rèn)值為1
# 作用: 返回以start開頭的均勻間隔step步長的值
for page in itertools.count(1):
    url = 'http://example.webscraping.com/view/-%d' % page
    html = download(url)
    if html is None:
        break
    else:
        # success -can scrap the result
        pass

# 這段代碼對ID進(jìn)行遍歷直到下載出錯停止,假設(shè)此時已經(jīng)到達(dá)最后一個國家頁面。
# 這種實現(xiàn)方式存在一個缺陷,那就是某些記錄可能已被刪除,數(shù)據(jù)庫ID之間并不是連續(xù)的。
# 此時只要訪問某個間隔點爬蟲就會立即退出。下面改進(jìn)代碼,連續(xù)發(fā)生多次下載錯誤后才退出程序
# 但這種爬蟲方式不是高效的做法

# maximum number of consecutive download errors allowed
max_errors = 5
# current number of consecutive download errors
num_errors = 0
for page in itertools.count(1):
    url = 'http://example.webscraping.com/view/-%d' % page
    html = download(url)
    if html is None:
        # recieved an error trying to download this webpage
        num_errors += 1
        if num_errors == max_errors:
            # reached maximum number of
            # consecutive errors so exit
            break
        else:
            # success -can scrape the result
            # ..
            num_errors = 0

3. 跟蹤網(wǎng)頁鏈接

鏈接爬蟲

# 以上兩種技術(shù)只要可用就應(yīng)當(dāng)使其進(jìn)行爬取,因為這兩種方法最小化了需要下載的網(wǎng)頁數(shù)量。
# 對于另一些網(wǎng)站,需要讓爬蟲模擬用戶行為,跟蹤鏈接,訪問感興趣的內(nèi)容


def link_crawler(seed_url, link_regex):
    crawl_queue = [seed_url]
    # keep track which URL's have seen before
    seen = set(crawl_queue)
    while crawl_queue:
        url = crawl_queue.pop()
        html = download(url)
        for link in get_links(html):
            # check if link matches expected regex
            if re.match(link_regex, link):
                # from absolute link
                link = urlparse.urljoin(seed_url, link)
                # check if have already seen this link
                if link not in seen:
                    seen.add(link)
                    crawl_queue.append(link)


def get_links(html):
    # Return a list of links from html
    # a regular expression to extract all links from the webpage
    webpage_regex = re.compile('<a[^]>+href=["\'](.*?)]["\']]', re.IGNORECASE)
    # list of all links from the webpage
    return webpage_regex.findall(html)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容