Python学习笔记--创建类:电影网站

来源:互联网 发布:厦门大学大数据实验室 编辑:程序博客网 时间:2024/06/01 08:23

本文使用python制作一个简单的电影网页,上面显示电影名字和海报,点击海报时,会播放预告片(预告片引自YouTube,播放预告片网络需要可以连上YouTube)
1、media.py

import webbrowserclass Movie:    def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):#构造函数        self.title = movie_title        self.storyline = movie_storyline        self.poster_image_url = poster_image        self.trailer_youtube_url = trailer_youtube    def show_trailer(self):        webbrowser.open(self.trailer_youtube_url)

2、fresh_tomatoes.py

import webbrowserimport osimport re# Styles and scripting for the pagemain_page_head = '''<!DOCTYPE html><html lang="en"><head>    <meta charset="utf-8">    <title>Fresh Tomatoes!</title>    <!-- Bootstrap 3 -->    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap-theme.min.css">    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>    <style type="text/css" media="screen">        body {            padding-top: 80px;        }        #trailer .modal-dialog {            margin-top: 200px;            width: 640px;            height: 480px;        }        .hanging-close {            position: absolute;            top: -12px;            right: -12px;            z-index: 9001;        }        #trailer-video {            width: 100%;            height: 100%;        }        .movie-tile {            margin-bottom: 20px;            padding-top: 20px;        }        .movie-tile:hover {            background-color: #EEE;            cursor: pointer;        }        .scale-media {            padding-bottom: 56.25%;            position: relative;        }        .scale-media iframe {            border: none;            height: 100%;            position: absolute;            width: 100%;            left: 0;            top: 0;            background-color: white;        }    </style>    <script type="text/javascript" charset="utf-8">        // Pause the video when the modal is closed        $(document).on('click', '.hanging-close, .modal-backdrop, .modal', function (event) {            // Remove the src so the player itself gets removed, as this is the only            // reliable way to ensure the video stops playing in IE            $("#trailer-video-container").empty();        });        // Start playing the video whenever the trailer modal is opened        $(document).on('click', '.movie-tile', function (event) {            var trailerYouTubeId = $(this).attr('data-trailer-youtube-id')            var sourceUrl = 'http://www.youtube.com/embed/' + trailerYouTubeId + '?autoplay=1&html5=1';            $("#trailer-video-container").empty().append($("<iframe></iframe>", {              'id': 'trailer-video',              'type': 'text-html',              'src': sourceUrl,              'frameborder': 0            }));        });        // Animate in the movies when the page loads        $(document).ready(function () {          $('.movie-tile').hide().first().show("fast", function showNext() {            $(this).next("div").show("fast", showNext);          });        });    </script></head>'''# The main page layout and title barmain_page_content = '''  <body>    <!-- Trailer Video Modal -->    <div class="modal" id="trailer">      <div class="modal-dialog">        <div class="modal-content">          <a href="#" class="hanging-close" data-dismiss="modal" aria-hidden="true">            <img src="https://lh5.ggpht.com/v4-628SilF0HtHuHdu5EzxD7WRqOrrTIDi_MhEG6_qkNtUK5Wg7KPkofp_VJoF7RS2LhxwEFCO1ICHZlc-o_=s0#w=24&h=24"/>          </a>          <div class="scale-media" id="trailer-video-container">          </div>        </div>      </div>    </div>    <!-- Main Page Content -->    <div class="container">      <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">        <div class="container">          <div class="navbar-header">            <a class="navbar-brand" href="#">Fresh Tomatoes Movie Trailers</a>          </div>        </div>      </div>    </div>    <div class="container">      {movie_tiles}    </div>  </body></html>'''# A single movie entry html templatemovie_tile_content = '''<div class="col-md-6 col-lg-4 movie-tile text-center" data-trailer-youtube-id="{trailer_youtube_id}" data-toggle="modal" data-target="#trailer">    <img src="{poster_image_url}" width="220" height="342">    <h2>{movie_title}</h2></div>'''def create_movie_tiles_content(movies):    # The HTML content for this section of the page    content = ''    for movie in movies:        # Extract the youtube ID from the url        youtube_id_match = re.search(            r'(?<=v=)[^&#]+', movie.trailer_youtube_url)        youtube_id_match = youtube_id_match or re.search(            r'(?<=be/)[^&#]+', movie.trailer_youtube_url)        trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match                              else None)        # Append the tile for the movie with its content filled in        content += movie_tile_content.format(            movie_title=movie.title,            poster_image_url=movie.poster_image_url,            trailer_youtube_id=trailer_youtube_id        )    return contentdef open_movies_page(movies):    # Create or overwrite the output file    output_file = open('fresh_tomatoes.html', 'w')    # Replace the movie tiles placeholder generated content    rendered_content = main_page_content.format(        movie_tiles=create_movie_tiles_content(movies))    # Output the file    output_file.write(main_page_head + rendered_content)    output_file.close()    # open the output file in the browser (in a new tab, if possible)    url = os.path.abspath(output_file.name)    webbrowser.open('file://' + url, new=2)

3、entertainment_enter.py

import mediaimport fresh_tomatoes#定义实例,实例名 = 文件名.类名()godfather  = media.Movie("The Godfather",                      "The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.",                      "https://images-na.ssl-images-amazon.com/images/M/MV5BZTRmNjQ1ZDYtNDgzMy00OGE0LWE4N2YtNTkzNWQ5ZDhlNGJmL2ltYWdlL2ltYWdlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SY1000_CR0,0,704,1000_AL_.jpg",                      "https://www.youtube.com/watch?v=_IqFJLdV13o")leon  = media.Movie("Leon",                   "Mathilda, a 12-year-old girl, is reluctantly taken in by Léon, a professional assassin, after her family is murdered. Léon and Mathilda form an unusual relationship, as she becomes his protégée and learns the assassin's trade.",                   "https://images-na.ssl-images-amazon.com/images/M/MV5BMjdjMGU3MGYtN2Y5ZC00MTE4LWE4YWQtMTBhMjc3MTk0ZDUwXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SY1000_SX664_AL_.jpg",                   "https://www.youtube.com/watch?v=yRABrgRcn5Y")titanic    = media.Movie("Titanic",                      "A seventeen-year-old aristocrat falls in love with a kind but poor artist aboard the luxurious, ill-fated R.M.S. Titanic.",                      "https://images-na.ssl-images-amazon.com/images/M/MV5BMDdmZGU3NDQtY2E5My00ZTliLWIzOTUtMTY4ZGI1YjdiNjk3XkEyXkFqcGdeQXVyNTA4NzY1MzY@._V1_SY1000_CR0,0,671,1000_AL_.jpg",                      "https://www.youtube.com/watch?v=2e-eXJ6HgkQ&t=7s")forrest_gump  = media.Movie("Forrest Gump",                      "While not intelligent, Forrest Gump has accidentally been present at many historic moments, but his true love, Jenny Curran, eludes him.",                      "https://images-na.ssl-images-amazon.com/images/M/MV5BYThjM2MwZGMtMzg3Ny00NGRkLWE4M2EtYTBiNWMzOTY0YTI4XkEyXkFqcGdeQXVyNDYyMDk5MTU@._V1_SY1000_CR0,0,757,1000_AL_.jpg",                      "https://www.youtube.com/watch?v=YNh9Es8Ut6U")inception  = media.Movie("Inception",                      "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",                      "https://images-na.ssl-images-amazon.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SY1000_CR0,0,675,1000_AL_.jpg",                      "https://www.youtube.com/watch?v=8hP9D6kZseM")black_swan  = media.Movie("Black Swan",                        "A committed dancer wins the lead role in a production of Tchaikovsky's \"Swan Lake\" only to find herself struggling to maintain her sanity.",                        "https://images-na.ssl-images-amazon.com/images/M/MV5BNzY2NzI4OTE5MF5BMl5BanBnXkFtZTcwMjMyNDY4Mw@@._V1_SY1000_CR0,0,674,1000_AL_.jpg",                        "https://www.youtube.com/watch?v=5jaI1XOB-bs")movies = [godfather, leon, forrest_gump, inception, titanic,  black_swan]fresh_tomatoes.open_movies_page(movies)

4、运行entertainment_enter.py后,打开浏览器并生成网页:
这里写图片描述

tips:

Google Python 格式指南:https://google.github.io/styleguide/pyguide.html