前言css
貓眼電影是淘寶聯合打造電影分類最全的電影的平臺,可以第一時間告知用戶,最新的電影上線時間。今天教你們獲取貓眼電影的即將上映的電影詳情。html
項目目標nginx
獲取貓眼電影的即將上映的電影詳情。ruby
項目準備網絡
軟件:PyCharmless
須要的庫:requests、lxml、random、timedom
插件:Xpathide
網站以下:函數
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循環遍歷這網址,實現多個網址請求。
項目實現
一、定義一個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()
二、隨機產生UserAgent。
for i in range(1, 50):
# ua.random,必定要寫在這裏,每次請求都會隨機選擇。
self.headers = {
'User-Agent': ua.random,
}
三、發送請求,獲取頁面響應。
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)
四、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 = '''【即將上映】
五、定義movie,保存打印數據。
movie = '''【即將上映】
電影名字: %s
主演:%s
類型:%s
詳情連接:https://maoyan.com%s
=========================================================
''' % (name, star, type,dowld)
print( movie)
六、random.randint()方法,設置時間延時。
time.sleep(random.randint(1, 3))
七、調用方法,實現功能。
html = self.get_page(url)self.parse_page(html)
效果展現
一、點擊綠色小三角運行輸入起始頁,終止頁。
二、運行程序後,結果顯示在控制檯,以下圖所示。
三、點擊藍色下載連接, 網絡查看詳情。
本文的文字及圖片來源於網絡,僅供學習、交流使用,不具備任何商業用途,版權歸原做者全部,若有問題請及時聯繫咱們以做處理。
做者:Python進階者