首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >爬虫篇 | 用Python爬超级搞笑的视频

爬虫篇 | 用Python爬超级搞笑的视频

作者头像
龙哥
发布2019-10-24 16:06:00
1.1K0
发布2019-10-24 16:06:00
举报
文章被收录于专栏:Python绿色通道Python绿色通道

最近整理一个爬虫系列方面的文章,不管大家的基础如何,我从头开始整一个爬虫系列方面的文章,让大家循序渐进的学习爬虫,小白也没有学习障碍.

爬虫篇:使用Python动态爬取某大V微博,再用词云分析

实战篇 | 用Xpath,bs4,正则三种方式爬51job

爬虫篇 | 动态爬取QQ说说并生成词云,分析朋友状况

爬虫篇 | 200 行代码实现一个滑动验证码

爬虫篇 | 学习Selenium并使用Selenium模拟登录知乎

爬虫篇 | Python使用正则来爬取豆瓣图书数据

爬虫篇 | 不会这几个库,都不敢说我会Python爬虫

爬虫篇 | Python现学现用xpath爬取豆瓣音乐

爬虫篇 | Python最重要与重用的库Request

爬虫篇 | Python爬虫学前普及

基础篇 | Python基础部分

这两天看到别人用Python下载视频,于是我也来试一下平时总是喜欢看内涵段子。这里正好有内涵视频:http://neihanshequ.com/video/

github源码地址:https://github.com/pythonchannel/python27/blob/master/dyamic/download_video

打开网址:http://neihanshequ.com/video/

开始分析:

  1. 数据方式 按下F12 可以看到 Network中 response返回的数据都是用html渲染好的,所以这样的数据,你没有办法直接获取到他的数据,你只能通过他对应的实际网址来抓取你需要的数据
  1. 视频字段 再分析网页源代码,可以找到视频对应的地址,获取把地址拿出来放到迅雷中下载,然后发现可以果然可以播放,这说明这个地址是没有错误的
  1. 获取视频细节 点击播放视频可以获得视频的大小,这样我们可以在下载的时候知道下载进度.
  1. 获取更多数据 因为这里请求的数据只能通过往下拉,点击可以获取到更多数据,这里就必须要用到Selenium来模拟点击.
# coding:utf-8
import datetime
import os
import threading
import time
from contextlib import closing

import requests
from lxml import etree
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class VideoDown(object):

    def __init__(self):
        self.first_position = 0
        self.count = 0
        self.threads = []
        self.content = []

    def load_data(self):

        video_url = 'http://neihanshequ.com/video/'
        driver = webdriver.Firefox()  # 获取浏览器驱动
        driver.maximize_window()
        driver.implicitly_wait(10)  # 控制间隔时间等待浏览器反映
        driver.get(video_url)

        while True:
            try:
                WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, 'loadMore')))
            except Exception as e:
                print e.message
                break

            js = 'window.scrollTo(0,document.body.scrollHeight)'
            driver.execute_script(js)
            time.sleep(10)

            source = etree.HTML(driver.page_source)
            divs = source.xpath('//*[@id="detail-list"]/li')

            for div in divs:
                self.count = self.count + 1
                print '第{}条数据'.format(str(self.count))
                title = div.xpath('./div/div[2]/a/div/p/text()')
                v_url = div.xpath('.//*[@class="player-container"]/@src')
                title = title[0] if len(title) > 0 else '无介绍'.format(str(self.count))
                v_url = v_url[0] if len(v_url) > 0 else ''
                self.do_thread(title, v_url)

            try:
                load_more = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, 'loadMore')))
                load_more.click()
                time.sleep(10)
            except Exception as e:
                print e.message
                break

    def do_thread(self, title, url):
        t = threading.Thread(target=self.down_video, args=(title, url))
        self.threads.append(t)
        t.start()

        for tt in self.threads:
            tt.join()

    def down_video(self, title, url):
        try:
            with closing(requests.get(url, stream=True)) as response:
                print url
                chunk_size = 1024
                content_size = int(response.headers['content-length'])

                video_path = u'D:/store/video00'
                # 判断文件夹是否存在。
                if not os.path.exists(video_path):
                    os.makedirs(video_path)

                file_name = video_path + u'/{}.mp4'.format(self.count)
                if os.path.exists(file_name) and os.path.getsize(file_name) == content_size:
                    print(u'跳过' + file_name)
                else:
                    down = DownProgress(title, content_size)
                    with open(file_name, "wb") as f:
                        for data in response.iter_content(chunk_size=chunk_size):
                            f.write(data)

                            down.refresh_down(len(data))
        except Exception as e:
            print e.message


class DownProgress(object):
    def __init__(self, file_name, file_size):
        self.file_name = file_name
        self.file_down = 0
        self.file_size = file_size

    def refresh_down(self, down):
        self.file_down = self.file_down + down
        progress = (self.file_down / float(self.file_size)) * 100.0
        status = u'下载完成' if self.file_down >= self.file_size else u'正在下载...'
        print u'文件名称:{},下载进度:{},下载状态:{}'.format(self.file_name, '%.2f' % progress, status)


if __name__ == '__main__':
    startTime = datetime.datetime.now()
    down = VideoDown()
    down.load_data()
    endTime = datetime.datetime.now()
    print '下载花费时间{}秒'.format((endTime - startTime).seconds)
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-10-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python绿色通道 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 开始分析:
相关产品与服务
验证码
腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档