首页 > 解决方案 > 在 Scrapy 中抓取复杂的注释

问题描述

我正在使用 Scrapy。例如,我想在页面上抓取评论:https ://www.thingiverse.com/thing:2/comments

我会抓取更多网站,所以我想要灵活的代码。

我不知道如何在不丢失有关“容器”评论和评论“深度”的信息的情况下抓取评论。

假设我将有 3 个字段。id_container,内容和深度。这些信息足以了解评论之间的关系。如何编码每条评论都会包含这些信息?

这个问题很笼统,所以任何提示都会很有用

标签: pythonscrapy

解决方案


为避免丢失层次结构信息,您可以先获取所有深度 1 的评论并变得更深入,例如:

from collections import OrderedDict
from pprint import pprint

def get_children_hierarchy(selector, depth=1):
    hierarchy = OrderedDict()
    children = selector.css(f'.depth-{depth}').xpath('..')
    for child in children:
        key = child.xpath('./@id').get()
        hierarchy[key] = get_children_hierarchy(child, depth+1)
    return hierarchy or None

pprint(get_children_hierarchy(response))

输出:

OrderedDict([('comment-2217537', None),
             ('comment-1518847', None),
             ('comment-1507448', None),
             ('comment-1233476', None),
             ('comment-1109024',
              OrderedDict([('comment-1554022', None),
                           ('comment-1215964', None)])),
             ('comment-874441', None),
             ('comment-712565',
              OrderedDict([('comment-731427',
                            OrderedDict([('comment-809279',
                                          OrderedDict([('comment-819752',
                                                        OrderedDict([('comment-1696778',
                                                                      None)]))]))]))])),
             ('comment-472013', None),
             ('comment-472012', OrderedDict([('comment-858213', None)])),
             ('comment-403673', None)])

然后,使用 comment id,您可以获得该特定评论所需的所有信息。


推荐阅读