如何在Scrapy中遍历兄弟标签爬取期刊编辑信息?
解决Scrapy爬取编辑角色与信息对应问题
因为页面中角色标签(h3)和对应的编辑信息标签(div.row.align-items-center)是兄弟关系,且同一角色下的所有编辑div都紧跟在该角色h3之后,直到下一个角色h3出现,你可以通过两种方式实现角色与编辑信息的关联:
方式一:遍历所有子节点维护当前角色
直接遍历#editors-section下的所有直接子元素,用变量记录当前角色,遇到h3就更新角色,遇到编辑div就绑定当前角色:
section_children = response.css('#editors-section > *') current_role = None editor_data = [] for child in section_children: # 识别角色标签h3 if child.css('h3'): current_role = child.css('h3::text').get().strip() # 识别编辑所在的div elif child.css('div.row.align-items-center'): if current_role: name = child.css('h4 a::text').get().strip() affiliation = child.css('p.mb-0::text').get().strip() editor_data.append({ 'role': current_role, 'name': name, 'affiliation': affiliation }) # 最终的编辑数据列表 print(editor_data)
方式二:用XPath筛选角色对应的编辑div
先获取所有角色h3,再通过XPath的following-sibling筛选出当前h3之后、下一个h3之前的所有编辑div:
roles = response.css('#editors-section h3') editor_data = [] for role in roles: current_role = role.css('::text').get().strip() # 筛选当前角色下的所有编辑div editors = role.xpath('./following-sibling::div[contains(@class, "row align-items-center") and count(preceding-sibling::h3)=count(current()/preceding-sibling::h3)+1]') for editor in editors: name = editor.css('h4 a::text').get().strip() affiliation = editor.css('p.mb-0::text').get().strip() editor_data.append({ 'role': current_role, 'name': name, 'affiliation': affiliation }) print(editor_data)
两种方式都能准确将每个编辑的信息与其对应的角色绑定,你可以根据习惯选择其中一种。
内容的提问来源于stack exchange,提问作者Harikrishnan V
相关产品推荐
相关产品推荐

