如何使用CSS选择器提取相同class属性div下的帖子数与粉丝数?
解决方案
可以通过CSS选择器实现对应字段提取,这里提供两种常用方案:
方案1:利用元素固定顺序匹配(结构不变的场景最简便)
三个accounts-table__count在父容器下的顺序固定,第一个为帖子数、第二个为粉丝数,直接通过:nth-child()伪类定位即可:
'posts': users.css('.accounts-table__count:nth-child(1)::text').get(default='').strip(), 'followers': users.css('.accounts-table__count:nth-child(2)::text').get(default='').strip(),
说明:::text取的是div下的首个文本节点,刚好对应数值部分,default=''可以避免数据为空时调用strip()报错。
方案2:关联子标签内容匹配(结构顺序可能变化的场景更稳定)
如果担心后续页面结构调整导致顺序变化,可以通过:has()伪类,匹配内部<small>标签内容对应的父容器,准确率更高(需要Scrapy版本≥2.7,底层parsel库支持:has语法):
'posts': users.css('.accounts-table__count:has(small:contains("posts"))::text').get(default='').strip(), 'followers': users.css('.accounts-table__count:has(small:contains("followers"))::text').get(default='').strip(),
如果你的Scrapy版本较低不支持:has,也可以先取所有count元素,过滤匹配small标签的内容再取数值:
def parse(self, response): for users in response.css('div.directory__card'): # 提前解析posts和followers count_nodes = users.css('.accounts-table__count') posts = '' followers = '' for node in count_nodes: label = node.css('small::text').get() value = node.css('::text').get(default='').strip() if label == 'posts': posts = value elif label == 'followers': followers = value yield { 'id': users.css('span::text').get().replace('@','').replace('.','-'), 'name': users.css('strong.p-name::text').get(), 'posts': posts, 'followers': followers, 'description': users.css('p::text').get(), 'fediverse': users.css('span::text').get(), 'link': users.css('a.directory__card__bar__name').attrib['href'], 'image': users.css('img.u-photo').attrib['src'], 'bg-image': users.css('img').attrib['src'], } for nextpage in response.css('span.next'): next_page = nextpage.css('a').attrib['href'] if next_page is not None: yield response.follow(next_page, callback=self.parse)
内容的提问来源于stack exchange,提问作者Gwynne
相关产品推荐
相关产品推荐

