最热猫眼电影——爬虫

看电影。。。

  • 一个人看电影的喜好类型和时长,与年龄有着某种联系,而热门电影的题材、类型,在一定程度上有更广的覆盖面,有较高的参考价值
  • 猫眼电影平台,是个相对不错的平台,具备整体性的参考价值

懂爬虫的人都懂网页数据分析思路,不再叙述
代码毕竟不是好用的
需要封装成普通人可直接使用的程序文件
降低使用难度
pyinstaller 这个库可以将Python代码封装成 .exe 文件在Windows平台上进行使用

封装过程:Python .py 文件打包成 .exe 文件(Windows平台,python 3.x)

下面贴上代码;若不懂请仔细看注释,还不行请自行学习爬虫基础

# -*- coding: utf-8 -*-
"""
 @Time : 2020/7/26 9:51
 @File : maoyan.py 
 @Software: PyCharm
"""
import os
import time
import random
import requests
from lxml import etree
from fake_useragent import UserAgent


class MaoyanSpider(object):
    def __init__(self):
        self.url = 'https://maoyan.com/films?showType=2&offset={}'
        ua = UserAgent(verify_ssl=False)
        for i in range(1, 3):
            self.headers = {
    
    
                'User-Agent': ua.random,
            }
        # 添加计数(页数)
        self.page = 1

    # 获取页面
    def get_page(self, url):
        # random.choice一定要写在这里,每次请求都会随机选择
        res = requests.get(url, headers=self.headers)
        res.encoding = 'utf-8'
        html = res.text
        self.parse_page(html)

    # 解析页面
    def parse_page(self, html):
        #  创建解析对象
        parse_html = etree.HTML(html)
        # 基准xpath节点对象列表
        dd_list = parse_html.xpath('//dl[@class="movie-list"]//dd')
        print(len(dd_list))
        movie_dict = {
    
    }
        # 依次遍历每个节点对象,提取数据
        for dd in dd_list:
            name = dd.xpath('.//div[@class="movie-hover-title"]//span[@class="name noscore"]/text()')[0].strip()
            star = dd.xpath('.//div[@class="movie-hover-info"]//div[@class="movie-hover-title"][3]/text()')[1].strip()
            type = dd.xpath('.//div[@class="movie-hover-info"]//div[@class="movie-hover-title"][2]/text()')[1].strip()
            dowld = dd.xpath('.//div[@class="movie-item-hover"]/a/@href')[0].strip()
            # print(movie_dict)
            movie = '''【即将上映】

电影名字: %s
主演:%s
类型:%s
详情链接:https://maoyan.com%s
=========================================================
                                   ''' % (name, star, type, dowld)
            print(movie)
            spider.file(movie)

    # 保存 最新猫眼电影.doc 文件
    def file(self, movie):
        # 判断 最新猫眼电影.doc 文件是否存在 不存在则创建
        filename = "./最新猫眼电影.doc"
        if not os.path.exists(filename):
            os.system(r"cd.>{}".format(filename))

        f = open('./最新猫眼电影.doc', 'a', encoding='utf-8')
        f.write(str(movie))
        print(str(movie))
        f.close()

    # 主函数
    def main(self):
        for offset in range(0, 90, 30):
            url = self.url.format(str(offset))
            self.get_page(url)
            print(url)
            print('第%d页完成' % self.page)
            # 请求延时
            time.sleep(random.randint(1, 3))
            self.page += 1


if __name__ == '__main__':
    spider = MaoyanSpider()
    spider.main()

猜你喜欢

转载自blog.csdn.net/qq_43562262/article/details/107590039