详解Python爬取并下载《电影天堂》3千多部电影

yizhihongxing

详解Python爬取并下载《电影天堂》3千多部电影

0. 简介

本文主要介绍如何使用Python来爬取并下载电影天堂网站上的电影资源,包括如何从首页获取分类信息和对应的电影列表,如何从电影列表页获取详细的电影信息和下载链接,并使用迅雷进行自动下载。

1. 准备工作

在进行爬取之前,需要安装一些必要的Python库和工具:

  • BeautifulSoup4: 用于解析HTML和XML文档
  • requests: 用于发送HTTP请求
  • selenium: 用于模拟浏览器进行数据采集(目前电影天堂需要动态加载)
  • pymongo: 如果需要将数据存入MongoDB

此外,需要下载安装Chrome浏览器和对应版本的ChromeDriver。

2. 获取分类及电影列表

首先需要从 https://www.dy2018.com 获取电影天堂的首页HTML内容,然后使用BeautifulSoup4解析获取各个分类信息及对应的电影列表页URL。

import requests
from bs4 import BeautifulSoup

url = "https://www.dy2018.com/"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 获取分类信息
categories = []
category_list = soup.find('div', class_='contain').find('div', class_='bd2').find_all('a')
for category in category_list:
    categories.append({
        'name': category.text,
        'url': category.get('href')
    })

# 获取电影列表页URL
movie_urls = []
for category in categories:
    response = requests.get(category['url'])
    soup = BeautifulSoup(response.text, 'html.parser')
    movie_list = soup.find_all('b', class_='title')
    for movie in movie_list:
        movie_url = movie.find('a').get('href')
        if movie_url.startswith('/html/'):
            movie_url = 'https://www.dy2018.com' + movie_url
        movie_urls.append({
            'category': category['name'],
            'url': movie_url
        })

3. 获取电影详细信息及下载链接

对于每个电影列表页,需要进入详细信息页并解析获取电影的详细信息和下载链接。这里使用selenium模拟浏览器进行数据采集。

from selenium import webdriver

# 创建Chrome浏览器实例
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")  # 以无头模式运行
browser = webdriver.Chrome(chrome_options=chrome_options)

# 遍历每个电影并获取详细信息和下载链接
movies = []
for movie_url in movie_urls:
    browser.get(movie_url['url'])
    soup = BeautifulSoup(browser.page_source, 'html.parser')
    movie_info_table = soup.find('div', id='Zoom').find_all('table')[0]

    # 获取电影标题、封面、评分、简介、类型、导演、演员、下载链接等信息
    movie_title = soup.find('div', class_='title_all').h1.font.text
    movie_cover = movie_info_table.find('img').get('src')
    movie_rating = soup.find('div', class_='rating').find_all('strong')[0].text
    movie_description = movie_info_table.find_all('td')[1].text.strip()
    movie_type = movie_info_table.find_all('tr')[0].find_all('a')
    movie_type = [t.text for t in movie_type]
    movie_director = movie_info_table.find_all('tr')[1].find_all('a')
    movie_director = [t.text for t in movie_director]
    movie_actors = movie_info_table.find_all('tr')[2].find_all('a')
    movie_actors = [t.text for t in movie_actors]
    movie_download_urls = soup.select('#Zoom table > tbody > tr > td > a')
    movie_download_urls = [{
        'name': a.text,
        'url': a.get('href')
    } for a in movie_download_urls if a.get('href').startswith('thunder:')]

    movies.append({
        'title': movie_title,
        'cover': movie_cover,
        'rating': movie_rating,
        'description': movie_description,
        'type': ','.join(movie_type),
        'director': ','.join(movie_director),
        'actors': ','.join(movie_actors),
        'download_urls': movie_download_urls
    })

4. 自动下载

对于每部电影,可以从其中选择一个下载链接进行下载。这里使用迅雷进行自动下载。

import os
import time
from urllib.parse import unquote
from selenium.webdriver.chrome.service import Service as ChromeService

thunder_path = "C:\\Program Files (x86)\\Thunder Network\\Thunder\\Program\\Thunder.exe"
chrome_path = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
download_dir = "D:\\Movies"

chrome_service = ChromeService(executable_path="C:\\chromedriver.exe")
chrome_driver = webdriver.Chrome(service=chrome_service, options=chrome_options)

for i, movie in enumerate(movies):
    print("Downloading movie: %d/%d" % (i + 1, len(movies)))
    download_url = unquote(movie['download_urls'][0]['url'], 'utf-8')
    chrome_driver.get(download_url)
    time.sleep(10)
    os.system('"%s" "%s"' % (thunder_path, download_url))

注意,需要修改thunder_path和download_dir变量的值,以便与本机环境相匹配。

示例

下面展示一个完整的代码示例,以搜索“玩具总动员”为例,获取电影详细信息并进行下载。

import os
import time
from urllib.parse import unquote
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium import webdriver
import requests
from bs4 import BeautifulSoup


class DyttSpider:
    def __init__(self):
        self.url = 'https://www.dy2018.com/'
        self.chrome_path = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
        self.thunder_path = "C:\\Program Files (x86)\\Thunder Network\\Thunder\\Program\\Thunder.exe"
        self.download_dir = "D:\\Movies"

    def run(self, query='玩具总动员'):
        categories, movies = self.parse_page(query)
        self.download_movies(movies)

    def parse_page(self, query):
        # 获取分类信息
        response = requests.get(self.url)
        soup = BeautifulSoup(response.text, 'html.parser')
        categories = []
        category_list = soup.find('div', class_='contain').find('div', class_='bd2').find_all('a')
        for category in category_list:
            categories.append({
                'name': category.text,
                'url': category.get('href')
            })

        # 搜索电影
        search_url = 'https://www.dy2018.com/e/search/index.php'
        post_data = {
            'keyboard': query,
            'show': 'title,smalltext',
            'tempid': '1',
            'tbname': 'article',
            'submit': '搜索',
        }
        response = requests.post(search_url, data=post_data)
        soup = BeautifulSoup(response.text, 'html.parser')
        movie_list = soup.find_all('b', class_='title')

        # 遍历每个电影并获取详细信息和下载链接
        movies = []
        for movie in movie_list:
            movie_url = movie.find('a').get('href')
            if movie_url.startswith('/html/'):
                movie_url = 'https://www.dy2018.com' + movie_url

            # 创建Chrome浏览器实例
            chrome_options = webdriver.ChromeOptions()
            chrome_options.add_argument("--headless")  # 以无头模式运行
            chrome_service = ChromeService(executable_path="C:\\chromedriver.exe")
            chrome_driver = webdriver.Chrome(service=chrome_service, options=chrome_options)

            chrome_driver.get(movie_url)
            soup = BeautifulSoup(chrome_driver.page_source, 'html.parser')
            movie_info_table = soup.find('div', id='Zoom').find_all('table')[0]

            # 获取电影标题、封面、评分、简介、类型、导演、演员、下载链接等信息
            movie_title = soup.find('div', class_='title_all').h1.font.text
            movie_cover = movie_info_table.find('img').get('src')
            movie_rating = soup.find('div', class_='rating').find_all('strong')[0].text
            movie_description = movie_info_table.find_all('td')[1].text.strip()
            movie_type = movie_info_table.find_all('tr')[0].find_all('a')
            movie_type = [t.text for t in movie_type]
            movie_director = movie_info_table.find_all('tr')[1].find_all('a')
            movie_director = [t.text for t in movie_director]
            movie_actors = movie_info_table.find_all('tr')[2].find_all('a')
            movie_actors = [t.text for t in movie_actors]
            movie_download_urls = soup.select('#Zoom table > tbody > tr > td > a')
            movie_download_urls = [{
                'name': a.text,
                'url': a.get('href')
            } for a in movie_download_urls if a.get('href').startswith('thunder:')]

            movies.append({
                'title': movie_title,
                'cover': movie_cover,
                'rating': movie_rating,
                'description': movie_description,
                'type': ','.join(movie_type),
                'director': ','.join(movie_director),
                'actors': ','.join(movie_actors),
                'download_urls': movie_download_urls
            })

            chrome_driver.quit()

        return categories, movies

    def download_movies(self, movies):
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--headless")  # 以无头模式运行
        chrome_service = ChromeService(executable_path="C:\\chromedriver.exe")
        chrome_driver = webdriver.Chrome(service=chrome_service, options=chrome_options)

        for i, movie in enumerate(movies):
            print("Downloading movie: %d/%d" % (i + 1, len(movies)))
            download_url = unquote(movie['download_urls'][0]['url'], 'utf-8')
            chrome_driver.get(download_url)
            time.sleep(10)
            os.system('"%s" "%s"' % (self.thunder_path, download_url))

        chrome_driver.quit()


if __name__ == '__main__':
    spider = DyttSpider()
    spider.run(query='玩具总动员')

输出结果为:

Downloading movie: 1/1

这里仅下载了一部电影,如果有多部电影需要下载,输出结果会有相应变化。同时可以发现,在程序运行完成之后,迅雷会自动打开并开始下载。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:详解Python爬取并下载《电影天堂》3千多部电影 - Python技术站

(0)
上一篇 2023年5月14日
下一篇 2023年5月14日

相关文章

  • Python基础教程之pip的安装和卸载

    那我就为你讲解一下“Python基础教程之pip的安装和卸载”: pip的安装和卸载 什么是pip Pip 是用于在 Python 环境中安装和管理软件包的软件。它类似于 Linux 中的 apt-get 或者 MacOS 中的 Homebrew。 安装pip 在Windows上安装pip 在 Windows 上,可以通过以下步骤安装 pip: 在浏览器中访…

    python 2023年5月14日
    00
  • Python程序运行原理图文解析

    下面是关于“Python程序运行原理图文解析”的详细攻略。 Python程序运行原理图文解析 程序的编译和解释 在讲解Python程序运行原理之前,我们需要先了解一下计算机语言的解释和编译两种机制。 编译: 在程序运行之前,编译器将源代码编译成本地处理器能够理解的机器码,然后再运行机器码。优点是运行速度快,缺点是需要在不同的平台上重新编译。 解释: 解释器将…

    python 2023年5月13日
    00
  • 煎蛋网妹子图爬虫总结

    这次是只用字符串查找的方式来找网页中图片链接的 1 #!/usr/bin/python 2 #coding:utf-8 3 import urllib.request 4 import os 5 import time 6 import random 7 8 def url_open(url): 9 # header = {} 10 # header[‘Us…

    爬虫 2023年4月10日
    00
  • 关于python3的ThreadPoolExecutor线程池大小设置

    关于Python 3的ThreadPoolExecutor线程池大小设置,主要涉及以下几个概念: 线程池:线程池是一种多线程编程模式,其中有一个工作线程在前台处理请求,而其他工作线程在后台处理请求。 ThreadPoolExecutor类:ThreadPoolExecutor是Python标准库concurrent.futures模块下的一个类,可以方便地创…

    python 2023年5月19日
    00
  • 爬虫再探之mysql简单使用

        在爬取数据量比较大时,用EXCEL存取就不太方便了,这里简单介绍一下python操作mysql数据库的一些操作。本人也是借助别人的博客学习的这些,但是找不到原来博客链接了,就把自己的笔记写在这里,这里感谢博文原创者。      import MySQLdb # 打开数据库连接 mypwd = input(“请输入数据库密码:”) # 这里只是避免代码…

    爬虫 2023年4月10日
    00
  • 使用python批量读取word文档并整理关键信息到excel表格的实例

    接下来我将为您详细讲解“使用python批量读取word文档并整理关键信息到excel表格”的实例教程。 一、准备工作 在开始实例之前,需要做以下几个准备工作: 安装Python 安装Python-docx库 安装openpyxl库 二、读取Word文档 首先,我们需要用Python读取Word文档中的内容。使用Python-docx库可以帮助我们读取Wor…

    python 2023年5月13日
    00
  • Python时间差中seconds和total_seconds的区别详解

    Python时间差中seconds和total_seconds的区别详解 在使用Python中的datetime库进行时间计算时,经常会遇到计算时间差(timedelta)的情况。其中,timedelta对象拥有seconds属性和total_seconds()方法,它们都可以用来计算时间差。本文将深入解析seconds和total_seconds之间的区别…

    python 2023年6月2日
    00
  • 将图片文件嵌入到wxpython代码中的实现方法

    将图片文件嵌入到wxPython代码中,有许多的方法,其中最常见的方法就是将图片转换为Base64编码的格式,在代码中引用该编码。这种方法可以确保图片随着程序的安装一同部署,避免图片文件遗失的风险。下面两个示例分别演示了将图片嵌入到wxPython应用程序中的基本步骤及代码具体实现。 示例1:在多状态按钮上添加不同背景图片 将需要使用的图片文件转换为Base…

    python 2023年5月20日
    00
合作推广
合作推广
分享本页
返回顶部