试图用相同的div抓取文本,但没有其他信息



此html有3个div,它们的名称相同accounts-table__count,但信息类型不同。

我正在尝试获取这个页面的帖子数和关注者数。有没有一种方法可以使用css选择器获取文本?

场地;https://mastodon.online/explore

<div class='directory__card__extra'>
<div class='accounts-table__count'>
629
<small>posts</small>
</div>
<div class='accounts-table__count'>
72
<small>followers</small>
</div>
<div class='accounts-table__count'>
<time class='time-ago' datetime='2021-05-18' title='May 18, 2021'>May 18, 2021</time>
<small>last active</small>
</div>
</div>

我的代码;

def parse(self, response):
for users in response.css('div.directory__card'):
yield {
'id': users.css('span::text').get().replace('@','').replace('.','-'),
'name': users.css('strong.p-name::text').get(),
'posts': ''              // this is the post count //
'followers': ''             // this is the follower count //
'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)

例如,在卡片上迭代,每个卡片都获得text形状的值,并过滤掉这些值。

raw_data = response.css(".directory__card")[0].css(".accounts-table__count::text").getall()
values = list(filter(lambda s: s != "", map(lambda s: s.strip(), raw_data)))

.accounts-table__count::text的css选择器中的一些值是空的,因为具有此类的div元素没有文本,但其中有其他html元素。

最新更新