python - 不能每个
每个评论的标签
问题描述
我正在尝试抓取视频的评论,除了每个特定评论的正文之外,我可以轻松地获取所有内容: 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)
我想获取每条评论的文本但不能,获取该部分的代码在正文字段中。
解决方案
不知道页面上的语言。但这里是使用 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 中的解析器。它可以独立使用。
推荐阅读
- react-native - React Native - 使用反应钩子搜索对象的数组
- batch-file - 本地刷新redis客户端的批处理文件
- python-3.x - 如何使用editpyxl将数据添加到现有的xlsm文件中?
- sql-server - 基于列和条件的组合查询多行
- rabbitmq - RabbitMQ - 我可以从不同的交易所发布事件吗
- requirejs - OroCRM 4.1 中的 Requirejs 问题
- c++ - STDOUT 未通过 C++ 中的套接字发送所有数据
- python - 有没有办法让我使用investpy 包从不同公司获取基本数据?
- swiftui - 图像旋转动画导致图像移动
- python - 如何在 Robot Framework 中设置带有特殊字符的变量