电影院要开工了,用Python看一看最近有什么刚上映的电影

前言css

猫眼电影是淘宝联合打造电影分类最全的电影的平台,可以第一时间告知用户,最新的电影上线时间。今天教你们获取猫眼电影的即将上映的电影详情。html

电影院要开工了,用Python看一看最近有什么刚上映的电影

 

项目目标nginx

获取猫眼电影的即将上映的电影详情。ruby

电影院要开工了,用Python看一看最近有什么刚上映的电影

 

项目准备网络

软件: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看一看最近有什么刚上映的电影

 

二、运行程序后,结果显示在控制台,以下图所示。

电影院要开工了,用Python看一看最近有什么刚上映的电影

 

三、点击蓝色下载连接, 网络查看详情。

电影院要开工了,用Python看一看最近有什么刚上映的电影

 

本文的文字及图片来源于网络,仅供学习、交流使用,不具备任何商业用途,版权归原做者全部,若有问题请及时联系咱们以做处理。

做者:Python进阶者

相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息