python - 在 Scrapy 中抓取复杂的注释
问题描述
我正在使用 Scrapy。例如,我想在页面上抓取评论:https ://www.thingiverse.com/thing:2/comments
我会抓取更多网站,所以我想要灵活的代码。
我不知道如何在不丢失有关“容器”评论和评论“深度”的信息的情况下抓取评论。
假设我将有 3 个字段。id_container,内容和深度。这些信息足以了解评论之间的关系。如何编码每条评论都会包含这些信息?
这个问题很笼统,所以任何提示都会很有用
解决方案
为避免丢失层次结构信息,您可以先获取所有深度 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
,您可以获得该特定评论所需的所有信息。
推荐阅读
- javascript - Javascript/Node.js 内部如何表示函数?
- node.js - Axios 将我连接到错误的端口
- javascript - 查找两个数组是否在数组中重复,然后选择它们
- sql-server - 无法生成 SSPI 上下文错误,但如果指定了 SPN 服务器名称则不会
- android - java.lang.ClassCastException: Activity cannot be cast to Adapter while trying to convert Activity to Fragment
- java - 如何使用android api将本地文件从外部目录上传到谷歌驱动器?
- c++ - c++中的第一个重复字符
- python - Kivy 应用程序运行后立即出现 Python 错误
- c - C 语言以二进制形式访问内存
- flutter - Flutter - CupertinoActionSheet / CupertinoActionSheetAction 背景颜色在设备上与模拟器中不同