python爬虫脚本下载YouTube视频

爬虫
python
YouTube视频

工作环境:

  • python 2.7.13

  • pip

  • lxml, 安装 pip install lxml,主要用xpath查找节点,可以使用re模块代替

  • pytube, 安装 pip install pytube

  • ***工具

参考:

源码:

  1. # coding: utf-8 

  2. __author__ = "zwzhou" 

  3. __date__ = "2017-03-19" 


  4. import urllib2 

  5. from pytube import YouTube 

  6. from pprint import pprint 

  7. from lxml import etree 

  8. import sys,getopt 


  9. def getHtml(url): 

  10. user_agent='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1284.0 Safari/537.13' 

  11. headers={'User-Agent':user_agent} 

  12. request=urllib2.Request(url,headers=headers) 

  13. response=urllib2.urlopen(request) 

  14. html=response.read() 

  15. return html 


  16. def getUrl(html): 

  17. global savepath 

  18. global maxNumber 

  19. global timeThreshold 

  20. global cur_count 

  21. global videoLists 

  22. tree=etree.HTML(html) 

  23. urllist=tree.xpath(u'//div[@class="thumb-wrapper"]/a/@href') 

  24. #print urllist 

  25. urllist_time=tree.xpath(u'//div[@class="thumb-wrapper"]/a/span/span/text()') 


  26. baseurl=r'https://www.youtube.com' 

  27. for (item_name,item_length) in zip(urllist,urllist_time): 

  28. #print item_name 

  29. #print item_length 

  30. try: 

  31. yt = YouTube(baseurl+item_name) 

  32. except: 

  33. print "Some thing wrong about the authority" 


  34. print("video name:"+yt.filename) 

  35. print("video time:"+item_length) 

  36. if yt.filename in videoLists: # 文件已经存在 

  37. print "This video has been downloaded!" 

  38. else: 

  39. if checktime(item_length): 

  40. video = yt.filter('mp4')[-1] 

  41. print("Now is loading %s------------>"%yt.filename) 

  42. video.download(savepath) 

  43. print("--------------->%sVideo is loaded!"%yt.filename) 

  44. cur_count+=1 

  45. videoLists.append(yt.filename) 

  46. if cur_count >= maxNumber:# 达到要求 

  47. print('There are %d videos downloaded!This task is completed!'%maxNumber) 

  48. # TODO: if necessary, the videoLists can be logged 

  49. sys.exit()  

  50. else: 

  51. print 'This video is too long and it will not be downloaded, just be ignored!' 

  52. if urllist: 

  53. getUrl(baseurl+urllist[0]) #下一个页面 



  54. def checktime(timelength): 

  55. global timeThreshold 

  56. strs=timelength.split(':') 

  57. time =int(strs[0])*60+int(strs[1]) 

  58. if time< timeThreshold: 

  59. return True 

  60. else: 

  61. return False 


  62. def usage(): 

  63. print ''' 

  64. usage: python dl_youtube [option] [arg] 

  65. options and args: 

  66. -s : download path 

  67. -t : time threshold of the video to be loaded, in seconds 

  68. -u : start url which to be crawled, it can be set more than one time 

  69. -n : when downloading is stop, i.e. how many videos will be downloaded, default is 10000. 

  70. -h : print this help message 

  71. ''' 


  72. if __name__ == "__main__": 

  73. start_urls=['https://www.youtube.com/watch?v=TThzH_sJo6o'] 

  74. videoLists=[] # 保存文件名,防止重复下载 

  75. # 初始值 

  76. savepath=r"D://MyDownloads" 

  77. maxNumber=10000 

  78. timeThreshold=240 

  79. cur_count=0 


  80. opts,args=getopt.getopt(sys.argv[1:],'hs:t:n:u:') 

  81. for op,value in opts: 

  82. if op == "-s": # 下载路径,如默认 D://MyDownloads 

  83. savepath=value 

  84. elif op == '-t': # 时常限制,默认240s 

  85. timeThreshold =int(value) 

  86. elif op == "-h": # help 

  87. usage() 

  88. sys.exit() 

  89. elif op == '-n': 

  90. maxNumber=int(value) 

  91. elif op == '-u': # 初始的搜索链接 

  92. start_urls.append(value) 


  93. for item in start_urls: 

  94. html = getHtml(item) 

  95. getUrl(html) 


使用

  1. python dl_youtube.py -n 10 -s D://MyDownloads -t 600 -u https://www.youtube.com/watch?v=TThzH_sJo6o 

将从页面 https://www.youtube.com/watch?v=TThzH_sJo6o 开始搜索下载10段时长小于6分钟的video保存到D://MyDownloads文件夹中。

python爬虫脚本下载YouTube视频的更多相关文章

  1. 使用python+ffmpeg+youtube-dl下载youtube上的视频

    一.准备工作 1.安装python,详见https://www.cnblogs.com/cnwuchao/p/10562416.html 2.安装ffmpeg,详见https://www.cnblog ...

  2. python爬虫之下载文件的方式总结以及程序实例

    python爬虫之下载文件的方式以及下载实例 目录 第一种方法:urlretrieve方法下载 第二种方法:request download 第三种方法:视频文件.大型文件下载 实战演示 第一种方法: ...

  3. Mac电脑如何快速下载YouTube视频

    如果你想下载一些教育类的视频资源,或者是一些学习的教程,那么YouTube是一个很好的视频资源平台.YouTube上面各种各样的资源都有,而且质量都很有保证,尤其是那些订阅量很多的人.可惜的是,You ...

  4. 使用在线工具下载YouTube视频

    YouTube上面有数不尽的视频资源,很多人都想从上面下载自己喜欢的视频,但是不得其法.那么,究竟怎样从YouTube上面下载视频呢?其实,一点也不难.只要你在Google上面搜索free youtu ...

  5. 安卓手机下载YouTube视频的3种方法

    作为全球最大的在线视频网站,YouTube上面的内容可真是应有尽有啊,从教学视频到个人手工艺品制作流程,从各种搞笑视频到电视连续集等等,包罗万象.如果你想下载YouTube视频到电脑上面的话,网上有很 ...

  6. Python:使用youtube-dl+ffmpeg+FQ软件下载youtube视频

    声明:本文所述内容都是从http://blog.csdn.net/u011475134/article/details/71023612博文中学习而来. 背景: 一同学想通过FQ软件下载一些youtu ...

  7. python下载youtube视频

    谷歌开源了一个新的数据集,BoundingBox,(网址在这里)这个数据集是经过人工标注的视频数据集,自然想将它尽快地运用在实际之中,那么首先需要将其下载下来:可以看到网址上给出的是csv文件,该文件 ...

  8. Python 爬虫——抖音App视频抓包

    APP抓包 前面我们了解了一些关于 Python 爬虫的知识,不过都是基于 PC 端浏览器网页中的内容进行爬取.现在手机 App 用的越来越多,而且很多也没有网页端,比如抖音就没有网页版,那么上面的视 ...

  9. Python 爬虫批量下载美剧 from 人人影视 HR-HDTV

    本人比較喜欢看美剧.尤其喜欢人人影视上HR-HDTV 的 1024 分辨率的高清双字美剧,这里写了一个脚本来批量获得指定美剧的全部 HR-HDTV 的 ed2k下载链接.并依照先后顺序写入到文本文件, ...

随机推荐

  1. HyperLogLog in Practice: Algorithmic Engineering of a State of The Art Cardinality Estimation Algorithm

    HyperLogLog参考下面这篇blog, http://blog.codinglabs.org/articles/algorithms-for-cardinality-estimation-par ...

  2. talib 中文文档(七):Overlap Studies Functions

    Overlap Studies Functions 重叠指标 BBANDS - Bollinger Bands 函数名:BBANDS 名称: 布林线指标 简介:其利用统计原理,求出股价的标准差及其信赖 ...

  3. BBS - 后台管理

    一.添加文章 注: 后台管理页面,应该有个新得 app /blog/backend/ # 文章列表页/blog/add_article/ # 添加文章 # 后台管理re_path(r'backend/ ...

  4. timedatectl — Control the system time and date

    timedatectl --help 的执行结果如下: timedatectl [OPTIONS...] COMMAND ... Query or change system time and dat ...

  5. 转!!spring @component 详解 默认初始化bean的名字 VNumberTask类 就是 VNumberTask

    参考链接:信息来源 今天碰到一个问题,写了一个@Service的bean,类名大致为:CUser xml配置: <context:component-scan base-package=&quo ...

  6. Spark Shuffle(一)ShuffleWrite:Executor如何将Shuffle的结果进行归并写到数据文件中去(转载)

    转载自:https://blog.csdn.net/raintungli/article/details/70807376 当Executor进行reduce运算的时候,生成运算结果的临时Shuffl ...

  7. keras实现不同形态的模型

    keras提供了Sequential线性的模型,但是有些网络需要多个输入,有些网络有多个输出,更甚之层与层之间有内部分支,这使得网络看起来像是层构成的图,而不是线性的堆叠.有些场景需要多模态的输入,这 ...

  8. SEO笔记:Anatomy of a URL

    Dr. Peter J. Meyers 原文链接:https://moz.com/blog/seo-cheat-sheet-anatomy-of-a-url 原文主要通过对比讲解 SEO优化后的URL ...

  9. #C++初学记录 (第一次测试)(A - 复习时间 )

    练习题目一 (A-复习时间) 为了能过个好年,xhd开始复习了,于是每天晚上背着书往教室跑.xhd复习有个习惯,在复习完一门课后,他总是挑一门更简单的课进行复习,而他复习这门课的效率为两门课的难度差的 ...

  10. LCS 最长公共子序列

    区别最长公共子串(连续) ''' LCS 最长公共子序列 ''' def LCS_len(x, y): m = len(x) n = len(y) dp = [[0] * (n + 1) for i ...