Чтобы не потерять информацию об иерархии, вы можете начать с получения всех комментариев глубины 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)])
Затем с комментарием id
, вы можете иметь всю информацию, которую вы хотите для этого конкретного комментария.