簡易爬蟲框架(二)

緊接著上回的文章,來書寫一個Callback并演示一下爬蟲吧。


實例分析

以一個實際的例子為主,即展示爬取一本小說為例子。


右鍵獲取xpath

通過xpath的獲取,就可以寫下索引頁面的callback函數,從而產生詳情頁的自定義Request,具體的事項請見上一回文章。

def qb5200_index_task(response: Response, spider: Request):
    """
    自定義的任務callback函數,這里是index函數
    :param response: requests返回的數據
    :param spider: 自定義的請求
    :return: yeild出新的自定義Request
    """
    html = etree.HTML(response.content.decode('gbk'))
    try:
        all_tr_tags = html.xpath('//div[@id="content"]//tr')
        for tr_tag in all_tr_tags[:2]:  # 請求一本小說,取前兩個element,第一個是表格頭,第二是小說
            td_temp = tr_tag.xpath('./td[@class="odd"]')
            if len(td_temp):
                name = td_temp[0].xpath('./a/text()')[0]
                url = td_temp[0].xpath('./a/@href')[0]
                yield Request(
                    url, name=name, folder=name, pipeline=FolderPipeline,
                    title=name, callback=qb5200_detail_task, headers={'Referer': spider.url},
                    category=DETAIL
                )
    except Exception as e:
        raise e

當拋出新的自定義Request后,管理器會將新的請求扔進Redis中,從而在下次的循環(huán)中彈出。

callback的結果處理

下輪循環(huán)彈出新的自定義Request

索引頁的Callback創(chuàng)建完了,新生成的請求需要詳情頁的Callback來決定之后的請求走向。

詳情頁的xpath

同樣以第一本小說為例子,寫下如下的詳情頁的Callback:

def qb5200_detail_task(response: Response, spider: Request):
    """
    自定義的任務callback函數,這里是detail函數
    :param response: requests返回的數據
    :param spider: 自定義的請求
    :return: yeild出新的自定義Request
    """
    html = etree.HTML(response.content.decode('gbk'))
    try:
        base_url = spider.url
        all_td_tags = html.xpath('//table//td')
        for td_tag in all_td_tags:
            a_tag = td_tag.xpath('./a')
            if len(a_tag):
                title = a_tag[0].xpath('./text()')[0]
                folder = title.replace('?', '?')\
                    .replace('!', '!')\
                    .replace('.', '。')\
                    .replace('*', 'x')  # 去除創(chuàng)建文件時沖突的特殊字符
                url = a_tag[0].xpath('./@href')
                yield Request(
                    base_url + url[0], name=spider.name, folder=folder, pipeline=FilePipeline,
                    title=title, callback=qb5200_text_task, headers={'Referer': spider.url},
                    category=TEXT
                )
    except Exception as e:
        raise e

注意category設置,這個將影響管理器處理這個請求的方式。TEXT代表了以文本的方式處理,在管理器中它會這樣處理。

TEXT類別的處理

當然很好奇上述拋出的Request中明明定義了qb5200_text_task這個Callback函數,但是沒有調用。這里是因為保持pipeline存儲的第一個參數是Response對象,所以將內容的處理放到了pipeline里。

callback的調用處

同時放上最后的qb5200_text_task的代碼:

def qb5200_text_task(response: Response, spider: Request):
    """
    自定義的任務callback函數,這里是真實數據請求函數,目前為針對于全本小說網的text文本
    :param response: requests返回的數據
    :param spider: 自定義的請求
    :return: yeild出新的自定義Request
    """
    html = etree.HTML(response.content.decode('gbk'))
    try:
        title_temp = html.xpath('//div[@id="title"]')
        if len(title_temp):
            title = title_temp[0].xpath('./text()')[0]
            content_temp = html.xpath('//div[@id="content"]')
            if len(content_temp):
                content = content_temp[0].xpath('string(.)')
                return {
                    "title": str(title),
                    "content": str(content)
                }
    except Exception as e:
        raise e

最后啟動運行初始代碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
 @File       : run.py
 @Time       : 2017/11/7 0007 20:40
 @Author     : Empty Chan
 @Contact    : chen19941018@gmail.com
 @Description: 運行spider
"""
from downloader import HttpDownloader
from manager import Manager
from pipeline import ConsolePipeline
from request import Request
from tasks import qb5200_index_task
from utils import INDEX

if __name__ == '__main__':
    '''定義初始的鏈接請求,初始化到manager中,然后run'''
    req = Request("http://www.qb5200.org/list/3.html", name='qb5200', category=INDEX,
                  pipeline=ConsolePipeline, callback=qb5200_index_task,
                  downloader=HttpDownloader)
    instance = Manager(req)
    instance.run()

結果展示:

爬取完成一本

Callback全部代碼

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
 @File       : tasks.py
 @Time       : 2017/10/21 0021 19:27
 @Author     : Empty Chan
 @Contact    : chen19941018@gmail.com
 @Description: 申明任務來執(zhí)行callback, 且必須滿足兩個參數,一個為requests請求的返回值,一個是自定義的spider請求
"""
import json
import click
from requests import Response
from lxml import etree
import re
import abc
from log_util import Log
from request import Request
from pipeline import FolderPipeline, ConsolePipeline, FilePipeline
from pipeline import FilePipeline
from utils import TEXT, IMAGE, VIDEO, INDEX, NEXT, DETAIL
qb5200_index_pat = re.compile(r'.*(\d+).*', re.MULTILINE)
qb5200_logger = Log("qb5200")


def qb5200_index_task(response: Response, spider: Request):
    """
    自定義的任務callback函數,這里是index函數
    :param response: requests返回的數據
    :param spider: 自定義的請求
    :return: yeild出新的自定義Request
    """
    html = etree.HTML(response.content.decode('gbk'))
    try:
        all_tr_tags = html.xpath('//div[@id="content"]//tr')
        for tr_tag in all_tr_tags[:2]:  # 請求一本小說,取前兩個element,第一個是表格頭,第二是小說
            td_temp = tr_tag.xpath('./td[@class="odd"]')
            if len(td_temp):
                name = td_temp[0].xpath('./a/text()')[0]
                url = td_temp[0].xpath('./a/@href')[0]
                yield Request(
                    url, name=name, folder=name, pipeline=FolderPipeline,
                    title=name, callback=qb5200_detail_task, headers={'Referer': spider.url},
                    category=DETAIL
                )
    except Exception as e:
        raise e


def qb5200_detail_task(response: Response, spider: Request):
    """
    自定義的任務callback函數,這里是detail函數
    :param response: requests返回的數據
    :param spider: 自定義的請求
    :return: yeild出新的自定義Request
    """
    html = etree.HTML(response.content.decode('gbk'))
    try:
        base_url = spider.url
        all_td_tags = html.xpath('//table//td')
        for td_tag in all_td_tags:
            a_tag = td_tag.xpath('./a')
            if len(a_tag):
                title = a_tag[0].xpath('./text()')[0]
                folder = title.replace('?', '?')\
                    .replace('!', '!')\
                    .replace('.', '。')\
                    .replace('*', 'x')
                url = a_tag[0].xpath('./@href')
                yield Request(
                    base_url + url[0], name=spider.name, folder=folder, pipeline=FilePipeline,
                    title=title, callback=qb5200_text_task, headers={'Referer': spider.url},
                    category=TEXT
                )
    except Exception as e:
        raise e


def qb5200_text_task(response: Response, spider: Request):
    """
    自定義的任務callback函數,這里是真實數據請求函數,目前為針對于全本小說網的text文本
    :param response: requests返回的數據
    :param spider: 自定義的請求
    :return: yeild出新的自定義Request
    """
    html = etree.HTML(response.content.decode('gbk'))
    try:
        title_temp = html.xpath('//div[@id="title"]')
        if len(title_temp):
            title = title_temp[0].xpath('./text()')[0]
            content_temp = html.xpath('//div[@id="content"]')
            if len(content_temp):
                content = content_temp[0].xpath('string(.)')
                return {
                    "title": str(title),
                    "content": str(content)
                }
    except Exception as e:
        raise e

有些東西寫得不好,算是很基礎的東西吧,希望后期能夠完善一下。感謝大家閱讀?。?!
放上Github地址。
大家下回見~~

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,502評論 19 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,716評論 25 709
  • scrapy學習筆記(有示例版) 我的博客 scrapy學習筆記1.使用scrapy1.1創(chuàng)建工程1.2創(chuàng)建爬蟲模...
    陳思煜閱讀 13,044評論 4 46
  • iOS網絡架構討論梳理整理中。。。 其實如果沒有APIManager這一層是沒法使用delegate的,畢竟多個單...
    yhtang閱讀 5,466評論 1 23
  • 若非一番寒徹骨,哪有梅花撲鼻香,我用歲月釀好酒,醉你余生不復憂。
    也很美閱讀 180評論 2 8

友情鏈接更多精彩內容