基於python3的簡單網路爬蟲示例

weixin_34187862發表於2017-02-22

網上用python寫爬蟲的示例大多數是基於python2.x版本的。由於爬蟲需要的庫在python3版本大都進行了重寫,所以各種包的位置和用法都有所改變。
筆者參照網上2.x版本的程式碼,寫了這個基於python3.x版本的簡單爬蟲示例,供大家參考。

# -*- coding:utf-8 -*-

import re
import urllib.error
import urllib.parse
import urllib.request


class QSBKSpider:

    # 初始化返回頁面用正規表示式
    pattern = re.compile(r'.<h2>(.*?)</h2>.*?<div class="content">(.*?)<!--(\d*?)-->.*?</div>'
                         r'(.*?)<div class="stats.*?class="number">(\d*?)</i>', re.S)
    # 初始化圖片正規表示式(過濾用)
    img_pattern = re.compile(r'<img.*?/>')

    # 初始化http請求頭,頁數等資訊
    def __init__(self):
        self.pageIndex = 1
        self.header = {
            'Connection': 'Keep-Alive',
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
            'Accept-Encoding': 'utf-8, deflate',
            'Host': 'www.qiushibaike.com',
        }

    # 取得頁面資料
    def get_page_content(self, page_index):
        try:
            self.pageIndex = page_index
            url = 'http://www.qiushibaike.com/textnew/' + self.pageIndex
            # 構建reqeust
            req = urllib.request.Request(url, None, self.header)
            # 發起請求
            rep = urllib.request.urlopen(req)
            # 讀取返回資料
            content_bytes = rep.read()
            page_content = content_bytes.decode('utf-8')
            return page_content
        # 列印通訊錯誤原因
        except urllib.error.HTTPError as e:
            print(e.code), (e.reason)
        except urllib.error.URLError as e:
            print(e.reason)
        finally:
            print('頁面獲取完畢')

    # 獲取當前頁面的所有段子
    def get_page_stories(self, content):
        # 對文字進行匹配
        re_results = re.findall(QSBKSpider.pattern, content)
        # 存放過濾掉圖片段子後的段子集合
        page_stories = []
        for result in re_results:
            if not QSBKSpider.img_pattern.search(result[3]):
                page_stories.append(result)
        return page_stories

    # 段子生成器.按需返回所有的段子
    def get_one_stroy(self, page_stories):
        for story in page_stories:
            print(story[1])
            yield story
        return 'done'

    # 主處理函式
    def app_start(self):
        page_index = input('請輸入頁碼')
        page_stories = self.get_page_stories(self.get_page_content(page_index))
        g = self.get_one_stroy(page_stories)
        while input('輸入回車讀取段子.停止讀取請輸入EOF') != 'EOF':
            try:
                next(g)
            except StopIteration as e:
                print('第%s頁故事讀取結束' % self.pageIndex)
                break
        print('讀取完畢,程式結束')

# start
qs = QSBKSpider()
qs.app_start()


該專案現在通過github進行管理。
你可以通過我的github個人頁面來獲取更多的關於python3.x版本的專案示例。歡迎follow。

相關文章