爬取某瓣电影中你好,李焕英电影的短评并生成词云

要爬取的目标链接:

项目结构:
爬取某瓣电影中你好,李焕英电影的短评并生成词云_第1张图片
其中img.png是背景图片,lhz.py是Python代码,lhz.text是爬取到的短评,msyh.ttc是字体文件,new_inclound.png是生成的词云图片。
字体文件和背景图片下载链接
提取码:8888
下面是完整的代码:

import requests   # 请求库,需要安装
from fake_useragent import UserAgent   # 构造user—Agent的库,需要安装
from lxml import etree   # 使用xpath()需要导入该库,需要安装
import time   # 使用time.sleep()使程序睡眠一段时间需要导入该库
import jieba  # 中文分词库,需要安装
import imageio   # 读取图片需要该库,需要安装
import wordcloud   # 制作词云的库,需要安装
from typing import NoReturn   # 类型标记的库,需要安装

class lhz():
    def __init__(self):
        """初始化"""
        self.next_page_url = "https://movie.douban.com/subject" \
                             "/34841067/comments?start=0&limit=20&status=P&sort=new_score"
        self.b = True

    def get_all_comment(self, url: str) -> NoReturn:
        """获取页面中的所有短评
           url:要提取短评的链接
        """
        response = requests.get(url, headers={
     'user-agent': UserAgent().chrome})
        e = etree.HTML(response.text, etree.HTMLParser())
        comm = e.xpath('//span[@class="short"]/text()')   # 使用xpath提取短评,结果是列表
        with open('lhz.text', mode='a', encoding='utf-8') as f:
            # 将列表中的每一个短评处理后写入文件中
            for i in comm:
                i.replace('\n', '')
                i += '\n'
                f.write(i)
        if self.b:
            # 使用xpath提取第一个页面中下一个页面的链接
            next_url = e.xpath('//div[@id="paginator"]/a/@href')
            self.b = False
        else:
            # 使用xpath提取非第一个页面中的下一个页面的链接
            next_url = e.xpath('//div[@id="paginator"]/a[3]/@href')
        if next_url:  # 如果提取到的下一个页面的链接不为空就递归提取
            time.sleep(0.5)   # 程序睡眠0.5秒
            # 构造下一个页面的链接
            next_url = ''.join(next_url).replace('&percent_type=', '')
            self.next_page_url = "https://movie.douban.com/subject" \
                                 "/34841067/comments{}".format(next_url)
            self.get_all_comment(self.next_page_url)  # 递归调用
            time.sleep(1)

    def make_clound(self) -> NoReturn:
        """绘制词云图"""
        with open('lhz.text', mode='r', encoding='utf-8') as f:  # 读取短评文件中的数据
            txt = f.read()
        txt_list = jieba.cut(txt)   # 分词
        string = ' '.join(txt_list)   # 分词后再使用空格它们重新连接成字符串

        img = imageio.imread('img.png')  # 读取图片

        wc = wordcloud.WordCloud(  # 配置词云参数
            width=1500,  # 词云图片的宽,单位是像素
            height=1000,  # 词云图片的高
            background_color='black',   # 背景颜色
            font_path='msyh.ttc',   # 字体文件的路径
            mask=img,  # 除白色部分之外的用来绘制词云
            scale=10,  # 按照比例进行放大画布,如设置为1.5,则长和宽都是原来画布的1.5倍
            stopwords={
     ',', '.', ',', '。', '!', '?', '?'},  # 设置停用词
        )
        wc.generate(string)   # 生成词云
        wc.to_file('new_inclound.png')   # 将词云保存到文件中

if __name__ == '__main__':
    """程序入口"""
    lhz = lhz()
    lhz.get_all_comment(lhz.next_page_url)
    lhz.make_clound()

上面用到了许多第三方库,大家需要使用pip安装,同时也需要注意你的字体文件路径和背景图片路径可能和我的不一样,要改为自己的。
同时,由于豆瓣有反爬措施,爬取到200多条时就需要登录,所以短评只有200多条,但这足够了!

下面是我的运行结果:

你可能感兴趣的:(Python爬虫,python,爬虫)