python爬虫爬取豆瓣最新评论并生成词云图代码
时间: 2025-01-27 17:07:12 浏览: 49
以下是一个使用Python爬取豆瓣最新评论并生成词云图的示例代码:
```python
import requests
from bs4 import BeautifulSoup
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 爬取豆瓣评论的函数
def get_comments(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
comments = soup.find_all('span', class_='short')
return [comment.get_text() for comment in comments]
# 生成词云的函数
def generate_wordcloud(text):
wordcloud = WordCloud(font_path='simhei.ttf', background_color='white', width=800, height=600).generate(text)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
# 主函数
def main():
url = 'https://movie.douban.com/subject/1292052/comments?status=P' # 替换为你要爬取的豆瓣电影页面URL
comments = get_comments(url)
text = ' '.join(comments)
text = ' '.join(jieba.cut(text))
generate_wordcloud(text)
if __name__ == '__main__':
main()
```
这段代码的主要功能如下:
1. 使用requests库爬取豆瓣评论页面。
2. 使用BeautifulSoup解析HTML内容,提取评论文本。
3. 使用jieba库对文本进行分词。
4. 使用wordcloud库生成词云图。
5. 使用matplotlib库显示生成的词云图。
使用这段代码时,请注意以下几点:
1. 确保安装了所需的Python库:requests, bs4, jieba, wordcloud, matplotlib。
2. 将font_path参数设置为本地中文字体文件路径,以确保中文能正确显示。
3. 修改url变量为你想要爬取的豆瓣电影页面URL。
阅读全文
相关推荐


















