1. 程式人生 > 實用技巧 >電影院要開工了,用Python看一看最近有什麼剛上映的電影

電影院要開工了,用Python看一看最近有什麼剛上映的電影

前言

貓眼電影是淘寶聯合打造電影分類最全的電影的平臺,能夠第一時間告知使用者,最新的電影上線時間。今天教大家獲取貓眼電影的即將上映的電影詳情。

專案目標

獲取貓眼電影的即將上映的電影詳情。

專案準備

軟體:PyCharm

需要的庫:requests、lxml、random、time

外掛:Xpath

網站如下:

https://maoyan.com/films?showType=2&offset={}

點選下一頁的按鈕,觀察到網站的變化分別如下:

https://maoyan.com/films?showType=2&offset=30
https://maoyan.com/films?showType=2&offset=60
https://maoyan.com/films?showType=2&offset=90

點選下一頁時,頁面每增加一頁offset=()每次增加30,所以可以用{}代替變換的變數,再用for迴圈遍歷這網址,實現多個網址請求。

專案實現

1、定義一個class類繼承object,定義init方法繼承self,主函式main繼承self。匯入需要的庫和網址,程式碼如下所示。

import requests
from lxml import etree

import time
import random

class MaoyanSpider(object):
def __init__(self):
self.url = "https://maoyan.com/films?showType=2&offset={}"

def main(self):
pass

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

2、隨機產生UserAgent。

 for i in range(1, 50):
# ua.random,一定要寫在這裡,每次請求都會隨機選擇。
self.headers = {
'User-Agent': ua.random,
}

3、傳送請求,獲取頁面響應。

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)

4、xpath解析一級頁面資料,獲取頁面資訊。

1)基準xpath節點物件列表。

 #  建立解析物件
parse_html = etree.HTML(html)
# 基準xpath節點物件列表
dd_list = parse_html.xpath('//dl[@class="movie-list"]//dd')

2)依次遍歷每個節點物件,提取資料。

 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 = '''【即將上映】

5、定義movie,儲存列印資料。

movie = '''【即將上映】

電影名字: %s

主演:%s

型別:%s
詳情連結:https://maoyan.com%s
=========================================================
''' % (name, star, type,dowld)
print( movie)

6、random.randint()方法,設定時間延時。

time.sleep(random.randint(1, 3))

7、呼叫方法,實現功能。

html=self.get_page(url)self.parse_page(html)

效果展示

1、點選綠色小三角執行輸入起始頁,終止頁。

2、執行程式後,結果顯示在控制檯,如下圖所示。

3、點選藍色下載連結, 網路檢視詳情。

本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯絡我們以作處理。

作者:Python進階者