這篇文章主要介紹了Python視頻爬蟲實現下載頭條視頻功能,涉及Python正則匹配、網路傳輸及檔案讀寫等相關操作技巧,需要的朋友可以參考下
本文執行個體講述了Python視頻爬蟲實現下載頭條視頻功能。分享給大家供大家參考,具體如下:
一、需求分析
抓取頭條短視頻
思路:
分析網頁源碼,尋找解析出視頻資源url(查看原始碼,搜mp4)
對該url發起請求,返回位元據
將位元據儲存為視頻格式
視頻連結:
http://video.eastday.com/a/170612170956054127565.html
二、代碼實現
# encoding: utf-8import sysreload(sys)sys.setdefaultencoding('utf-8')import requestsimport reimport timetime1=time.time()main_url = 'http://video.eastday.com/a/170612170956054127565.html'resp = requests.get(main_url)#沒有這行,列印的結果中文是亂碼resp.encoding = 'utf-8'html = resp.textlink = re.findall(r'var mp4 = "(.*?)";', html)[0]link = 'http:'+linkdest_resp = requests.get(link)#視頻是位元據流,content就是為了擷取位元據的方法data = dest_resp.content#儲存資料的路徑及檔案名稱path = u'C:/趙麗穎.mp4'f = open(path, 'wb')f.write(data)f.close()time2 = time.time()print u'ok,下載完成!'print u'總共耗時:' + str(time2 - time1) + 's
"D:\Program Files\Python27\python.exe" D:/PycharmProjects/learn2017/testwechat.py
ok,下載完成!
總共耗時:3.20499992371s
Process finished with exit code 0
成功下載可以播放~