欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python 抓取知乎指定回答下視頻的方法

 更新時間:2020年07月09日 11:17:05   作者:Leetao  
這篇文章主要介紹了python 抓取知乎指定回答下視頻的方法,文中講解非常詳細,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下

前言

現(xiàn)在知乎允許上傳視頻,奈何不能下載視頻,好氣哦,無奈之下研究一下了,然后擼了代碼,方便下載視頻保存。

接下來以 貓為什么一點也不怕蛇? 回答為例,分享一下整個下載過程。

調試一下

打開 F12, 找到光標,如下圖:

然后將光標移動到視頻上。如下圖:

咦這是什么?視野中出現(xiàn)了一條神秘的鏈接: https://www.zhihu.com/video/xxxxx,讓我們將這條鏈接復制到瀏覽器上,然后打開:

似乎這就是我們要找的視頻,不要著急,讓我們看一看,網(wǎng)頁的請求,然后你會發(fā)現(xiàn)一個很有意思的請求(重點來了):

讓我們自己看一下數(shù)據(jù)吧:

{
	"playlist": {
		"ld": {
			"width": 360,
			"format": "mp4",
			"play_url": "https://vdn.vzuu.com/LD/05fc411e-d8e0-11e8-bb8b-0242ac112a0b.mp4?auth_key=1541477643-0-0-987c2c504d14ab1165ce2ed47759d927&expiration=1541477643&disable_local_cache=1",
			"duration": 17,
			"size": 1123111,
			"bitrate": 509,
			"height": 640
		},
		"hd": {
			"width": 720,
			"format": "mp4",
			"play_url": "https://vdn.vzuu.com/HD/05fc411e-d8e0-11e8-bb8b-0242ac112a0b.mp4?auth_key=1541477643-0-0-8b8024a22a62f097ca31b8b06b7233a1&expiration=1541477643&disable_local_cache=1",
			"duration": 17,
			"size": 4354364,
			"bitrate": 1974,
			"height": 1280
		},
		"sd": {
			"width": 480,
			"format": "mp4",
			"play_url": "https://vdn.vzuu.com/SD/05fc411e-d8e0-11e8-bb8b-0242ac112a0b.mp4?auth_key=1541477643-0-0-5948c2562d817218c9a9fc41abad1df8&expiration=1541477643&disable_local_cache=1",
			"duration": 17,
			"size": 1920976,
			"bitrate": 871,
			"height": 848
		}
	},
	"title": "",
	"duration": 17,
	"cover_info": {
		"width": 720,
		"thumbnail": "https://pic2.zhimg.com/80/v2-97b9435a0c32d01c7c931bd00120327d_b.jpg",
		"height": 1280
	},
	"type": "video",
	"id": "1039146361396174848",
	"misc_info": {}
}

沒錯了,我們要下載的視頻就在這里面,其中 ld 代表普清,sd 代表標清, hd 代表高清,把相應鏈接再次在瀏覽器打開,然后右鍵保存就可以下載視頻了。

代碼

知道整個流程是什么樣子,接下來擼代碼的過程就簡單了,這里就不過再做過多解釋了,直接上代碼:

# -*- encoding: utf-8 -*-

import re
import requests
import uuid
import datetime


class DownloadVideo:

  __slots__ = [
    'url', 'video_name', 'url_format', 'download_url', 'video_number',
    'video_api', 'clarity_list', 'clarity'
  ]

  def __init__(self, url, clarity='ld', video_name=None):
    self.url = url
    self.video_name = video_name
    self.url_format = "https://www.zhihu.com/question/\d+/answer/\d+"
    self.clarity = clarity
    self.clarity_list = ['ld', 'sd', 'hd']
    self.video_api = 'https://lens.zhihu.com/api/videos'

  def check_url_format(self):
    pattern = re.compile(self.url_format)
    matches = re.match(pattern, self.url)
    if matches is None:
      raise ValueError(
        "鏈接格式應符合:https://www.zhihu.com/question/{number}/answer/{number}"
      )
    return True

  def get_video_number(self):
    try:
      headers = {
        'User-Agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
      }
      response = requests.get(self.url, headers=headers)
      response.encoding = 'utf-8'
      html = response.text
      video_ids = re.findall(r'data-lens-id="(\d+)"', html)
      if video_ids:
        video_id_list = list(set([video_id for video_id in video_ids]))
        self.video_number = video_id_list[0]
        return self
      raise ValueError("獲取視頻編號異常:{}".format(self.url))
    except Exception as e:
      raise Exception(e)

  def get_video_url_by_number(self):
    url = "{}/{}".format(self.video_api, self.video_number)

    headers = {}
    headers['Referer'] = 'https://v.vzuu.com/video/{}'.format(
      self.video_number)
    headers['Origin'] = 'https://v.vzuu.com'
    headers[
      'User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'
    headers['Content-Type'] = 'application/json'

    try:
      response = requests.get(url, headers=headers)
      response_dict = response.json()
      if self.clarity in response_dict['playlist']:
        self.download_url = response_dict['playlist'][
          self.clarity]['play_url']
      else:
        for clarity in self.clarity_list:
          if clarity in response_dict['playlist']:
            self.download_url = response_dict['playlist'][
              self.clarity]['play_url']
            break
      return self
    except Exception as e:
      raise Exception(e)

  def get_video_by_video_url(self):
    response = requests.get(self.download_url)
    datetime_str = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
    if self.video_name is not None:
      video_name = "{}-{}.mp4".format(self.video_name, datetime_str)
    else:
      video_name = "{}-{}.mp4".format(str(uuid.uuid1()), datetime_str)
    path = "{}".format(video_name)
    with open(path, 'wb') as f:
      f.write(response.content)

  def download_video(self):

    if self.clarity not in self.clarity_list:
      raise ValueError("清晰度參數(shù)異常,僅支持:ld(普清),sd(標清),hd(高清)")

    if self.check_url_format():
      return self.get_video_number().get_video_url_by_number().get_video_by_video_url()


if __name__ == '__main__':
  a = DownloadVideo('https://www.zhihu.com/question/53031925/answer/524158069')
  print(a.download_video())

結語

代碼還有優(yōu)化空間,這里面我只是下載了回答中的第一個視頻,理論上應該存在一個回答下可以有多個視頻的。如果還有什么疑問或者建議,可以多多交流。

以上就是python 抓取知乎指定回答下視頻的方法的詳細內容,更多關于python 抓取視頻的資料請關注腳本之家其它相關文章!

相關文章

  • Python的條件語句與運算符優(yōu)先級詳解

    Python的條件語句與運算符優(yōu)先級詳解

    這篇文章主要介紹了Python的條件語句與運算符優(yōu)先級,是Python入門學習中的基礎知識,需要的朋友可以參考下
    2015-10-10
  • Python排序搜索基本算法之堆排序實例詳解

    Python排序搜索基本算法之堆排序實例詳解

    這篇文章主要介紹了Python排序搜索基本算法之堆排序,結合實例形式詳細分析了堆排序的原理、Python實現(xiàn)方法及相關操作注意事項,需要的朋友可以參考下
    2017-12-12
  • Python連接es之查詢方式示例匯總

    Python連接es之查詢方式示例匯總

    這篇文章主要為大家介紹了Python連接es之查詢方式示例匯總詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-05-05
  • Python標準庫之隨機數(shù) (math包、random包)介紹

    Python標準庫之隨機數(shù) (math包、random包)介紹

    這篇文章主要介紹了Python標準庫之隨機數(shù) (math包、random包)介紹,本文講解了math包的常用函數(shù),同時給出了random包的使用例子,需要的朋友可以參考下
    2014-11-11
  • Zookeeper接口kazoo實例解析

    Zookeeper接口kazoo實例解析

    這篇文章主要介紹了Zookeeper接口kazoo實例解析,簡單介紹了Zookeeper接口接口的開發(fā),然后分享了相關實例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-01-01
  • python 中xpath爬蟲實例詳解

    python 中xpath爬蟲實例詳解

    這篇文章主要介紹了python實例:xpath爬蟲實例,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-08-08
  • Python切片知識解析

    Python切片知識解析

    這篇文章主要介紹了Python切片知識解析的相關資料,需要的朋友可以參考下
    2016-03-03
  • Python一行代碼實現(xiàn)自動發(fā)郵件功能

    Python一行代碼實現(xiàn)自動發(fā)郵件功能

    最近在自己學習Python爬蟲,學到了用Python發(fā)送郵件,覺得這個可能以后比較實用。所以這篇文章主要給大家介紹了如何通過Python一行代碼實現(xiàn)自動發(fā)郵件功能的相關資料,需要的朋友可以參考下
    2021-05-05
  • 詳解python中__name__的意義以及作用

    詳解python中__name__的意義以及作用

    這篇文章主要介紹了詳解python中__name__的意義以及作用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-08-08
  • python 常用的異步框架匯總整理

    python 常用的異步框架匯總整理

    自從python3推出關于異步編程的新語法之后,關于異步web框架也是如雨后春筍一般爆發(fā),關于 異步框架的性能也日漸激烈。今天就整理關于 python 的異步框架。
    2021-06-06

最新評論