首页 > 解决方案 > 不能每个

每个评论的标签

问题描述

我正在尝试抓取视频的评论,除了每个特定评论的正文之外,我可以轻松地获取所有内容: https ://tamasha.com/v/KGbXY

from scrapy.selector import Selector

    def crawl_comment(self, video_id):
        video_url = f"https://www.tamasha.com/v/{video_id}"
        # response = self.request.get_request(video_url, proxy=self.proxy, timeout=30, headers=None)
        response = self.request.get_request(video_url, timeout=30, headers=None)
        if response.status_code == 404:
            raise VideoNotFoundException()
        comment_information = Selector(text=response.text).xpath(
            '//*[@class="comment-item"]').getall()
        comment_data_list = []
        for comment_info in comment_information:
            video_id = video_id
            author_username = None
            try:
                author_username = Selector(text=comment_info).xpath('string(//*[@class="user-name"])').get()
            except:
                pass
            author_id = None
            try:
                author_id = Selector(text=comment_info).xpath('//*[@class="user-name"]/@href').get()
                author_id = author_id.split('/')[-1]
            except:
                pass
            date = Selector(text=response.text).xpath('//*[@class="comment-time"]/text()').get()
            body = Selector(text=response.text).css('#commentBox > div:nth-child(2) > div.more-comment > p').get
            id = Selector(text=response.text).xpath('//*[@class="comment-item"]/@data-comment-id').get()
            comment_data_list.append({
                'author_username': author_username,
                'author_id': author_id,
                'date': date,
                'body': body,
                'id': id,
                'video_id': video_id
            })
        print(comment_data_list)

我想获取每条评论的文本但不能,获取该部分的代码在正文字段中。

标签: pythonweb-scrapingscrapy

解决方案


不知道页面上的语言。但这里是使用 CSS 选择器提取评论的方法。

# selector is `Selector(text=response.text)`
selector.css('div.comment-item > .comment .comment-header + p::text').getall()

# explanation of css selector
# >, direct child
# space, descendent
# +, adjacent sibling

这是输出

# the second comment seems to be a comment replay
['چه خوب بودن همشون', 'عالی بودن', 'nice']

顺便说一句,你不是scrapy只使用解析器吗?在 Scrapy 中,Response.xpath()Selector(response_text).xpath()自动调度调用。

如果您不使用scrapy,而只需要解析器。pip install parsel, 并使用parsel.Selector. parsel是集成在 Scrapy 中的解析器。它可以独立使用。


推荐阅读