python爬取晋江文学城小说评论(情绪分析)

  • Post category:Python

这个任务是将Python程序用于爬取晋江文学城小说评论,并进行情绪分析的示例。

简介

本示例使用Python的requests和BeautifulSoup库来爬取晋江文学城小说评论数据,并使用情感分析Python的TextBlob库来计算评论的情感得分。情感得分是一个介于-1(非常消极)和1(非常积极)之间的分数。

依赖项

在运行这个示例之前,你需要安装这些库:

  • requests
  • beautifulsoup4
  • textblob

步骤

以下是爬取与情绪分析晋江文学城小说评论的完整步骤:

第1步:获取小说评论页面的网址

将要获取的小说页面作为输入,从页面中获取该页面的评论URL

import requests
from bs4 import BeautifulSoup

# 定义一个函数,用于获取小说页面的评论URL
def get_comments_url(novel_url):
    # 发送GET请求来获取小说页面
    response = requests.get(novel_url)
    # 使用BeautifulSoup解析HTML
    soup = BeautifulSoup(response.text, 'html.parser')
    # 查找包含评论的元素
    comments_elem = soup.find('a', attrs={'class': 'j_chapterReview'})
    # 获取评论URL
    comments_url = f"https:{comments_elem['href']}"
    return comments_url

第2步:获取所有评论

使用上一步中的评论URL,发送GET请求来获取所有的评论:

# 定义一个函数,用于获取所有的评论
def get_all_comments(url, page_num=1, comments=[]):
    # 发送GET请求来获取评论
    response = requests.get(url.format(page_num))
    # 如果返回码不是200,则停止递归并返回所有评论
    if response.status_code != 200:
        return comments
    # 使用BeautifulSoup解析HTML
    soup = BeautifulSoup(response.text, 'html.parser')
    # 找到在这个页面所有的评论
    new_comments = soup.find_all('span', attrs={'class': 'short-content'})
    # 将新的评论添加到评论列表中
    comments.extend([comment.text for comment in new_comments])
    # 递归获取下一页评论
    return get_all_comments(url, page_num + 1, comments)

第3步:使用TextBlob库计算评论情感得分

使用TextBlob库来计算每个评论的情感得分:

# 导入TextBlob库
from textblob import TextBlob

# 定义一个函数,用于计算一段文本的情感得分
def get_sentiment(text):
    blob = TextBlob(text)
    return blob.sentiment.polarity

# 计算所有评论的情感得分并返回平均分
def get_average_sentiment(comments):
    sentiment_scores = [get_sentiment(comment) for comment in comments]
    avg_sentiment = sum(sentiment_scores) / len(sentiment_scores)
    return avg_sentiment

示例

用于爬取晋江文学城小说《官道百度云》的评论:

novel_url = 'http://www.jjwxc.net/onebook.php?novelid=3942573'
comments_url = get_comments_url(novel_url)
comments = get_all_comments(comments_url)
sentiment_score = get_average_sentiment(comments)
print(f"官道百度云的情感得分为:{sentiment_score}")

用于爬取晋江文学城小说《元尊》的评论:

novel_url = 'http://www.jjwxc.net/onebook.php?novelid=3596651'
comments_url = get_comments_url(novel_url)
comments = get_all_comments(comments_url)
sentiment_score = get_average_sentiment(comments)
print(f"元尊的情感得分为:{sentiment_score}")

注意:这些示例需要在晋江文学城中提供的链接中使用其他小说的页面去替换novel_url中的链接。