PySpider 抓取结果数据预处理

抓取后的数据内容处理,基本处理分以下几种规则:

  • 删除无用的结点,例如 script style 等
  • 原样保留的结点,例如 table img 等
  • 删除带指定 class 的结点

到这一个完整的处理方法也就出来了:

def custom_text(self, doc):
    # 无用的标签结点
    ignore_tags = ['script', 'style']
    # 原样输出的标签结点
    raw_tags = ['table', 'img']
    # 带指定 class 的标签结点
    ignore_class = ['pstatus']

    for tag in ignore_tags:
        doc.find(tag).remove()
    for clazz in ignore_class:
        doc.find('.' + clazz).remove()
    doc.find('a').remove_attr('href')

    text = []
    def add_text(tag, no_tail=False):
        if not isinstance(tag, _Comment):
            if tag.tag in raw_tags:
                text.append(etree.tostring(tag, with_tail=False))
            elif tag.text:
                text.append(tag.text)
        for child in tag.getchildren():
            add_text(child)
        if not no_tail and tag.tail:
            text.append(tag.tail)

    for tag in doc:
        add_text(tag, no_tail=True)
    result = ''
    for t in text:
        result += t.strip()
        if len(t.strip()) > 1:
            result += "<br/>"
    return result

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注