【Python】爬取TapTap原神评论并生成词云分析

序言

本来是想爬B站的,但是B站游戏区的评论好像是动态方式加载,分析了一通没搞懂怎么爬,所以转到了TapTap,TapTap评论页通过URL来定位,非常容易拼接URL去获取想要的页面,所以这次爬取的对象选为TapTap。

目标

爬取TapTap社区原神游戏下玩家的评论,生成词频,词云,可视化关键词。

步骤

爬虫

目标是爬取用户名、评分、时间、评论四个维度的信息,首先要获取到页面上的评论列表:

response = requests.get(self.comments_url % page, headers=self.headers)
print('访问第', page, '页,状态是', response.status_code, '。')
time.sleep(random.random())
html = etree.HTML(response.text)
contents = html.xpath('//ul[contains(@class, "taptap-review-list")]/li')

然后遍历列表解析出各个字段:

user = content.xpath('.//a[@class="taptap-user-name"]/text()')[0] or '无名氏'
score = content.xpath('.//div[@class="item-text-score"]/i[@class="colored"]/@style')[0][7:9]
score = int(score) / 14
comment_time = content.xpath('(.//span)[4]/text()')[0]
comment = content.xpath('(.//div[@class="item-text-body"])[1]/p/text()')
comment = '\n'.join(comment)

最后把数据存入文件供之后使用:

comment_dir = {
   'user': users, 'score': scores, 'time': times, 'comment': comments}
comment_df = pd.DataFrame(comment_dir)
comment_df.to_csv('./tables/taptap_comments.csv')
comment_df['comment'].to_csv('./tables/comments.csv', index=False)
分词

爬虫拿到了数据,接下来就要对数据进行分词,这里使用的是jieba库:

jieba.load_userdict('./dictionary/my_dict.txt')
with open('./tables/comments.csv', 'r'
  • 5
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
要使用Python爬取Taptap论坛数据,可以按照以下步骤进行: 1. 安装必要的Python库:requests、BeautifulSoup和pandas。可以使用pip命令来安装这些库。 2. 找到需要爬取的Taptap论坛页面的URL。例如,我们可以爬取“神都夜行录”游戏的论坛页面:https://www.taptap.com/app/1369/topic。 3. 使用requests库发送HTTP请求,获取网页HTML代码。可以使用get()方法来发送GET请求,然后使用.text属性获取HTML代码。 4. 使用BeautifulSoup库解析HTML代码,提取需要的数据。可以使用find()或find_all()方法来查找HTML标签,然后使用.text属性获取标签的文本内容。 5. 将提取的数据存储到CSV文件中。可以使用pandas库创建DataFrame对象,然后使用to_csv()方法将数据保存为CSV文件。 以下是一个示例代码,可以爬取“神都夜行录”游戏的论坛页面,并将发帖人、发帖时间和帖子内容保存到CSV文件中: ```python import requests from bs4 import BeautifulSoup import pandas as pd url = 'https://www.taptap.com/app/1369/topic' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') posts = [] for post in soup.find_all('div', class_='topic-item'): author = post.find('div', class_='author-name').text.strip() time = post.find('span', class_='created-at').text.strip() content = post.find('div', class_='topic-item-body').text.strip() posts.append({'author': author, 'time': time, 'content': content}) df = pd.DataFrame(posts) df.to_csv('shendu.csv', index=False) ``` 运行以上代码后,将会在当前目录下生成一个名为“shendu.csv”的CSV文件,其中包含了论坛页面中所有帖子的发帖人、发帖时间和帖子内容。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值