


Learn how to use Python to capture videos with specified answers on Zhihu
Preface
Now Zhihu allows uploading videos, but I can’t download videos. I’m so angry, so I researched in desperation. After a while, I typed the code to make it easier to download and save the video.
Next, why are cats not afraid of snakes at all? Answer as an example and share the entire download process.
Related learning recommendations: python video tutorial
Debug it
Open F12 , find the cursor, as shown below:
and then move the cursor to the video. As shown below:
Hey what is this? A mysterious link appeared in the field of vision: https://www.zhihu.com/video/xxxxx, let us copy this link to the browser, and then open it:
It seems that this is the video we are looking for, don’t worry, let’s take a look at the request of the web page, and then you will find a very interesting request (here comes the focus):
Let us take a look at the data ourselves:
{ "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": {} }
Yes, the video we want to download is here, where ld represents common definition, sd represents standard definition, and hd represents high definition. Put the corresponding Open the link in the browser again, then right-click and save to download the video.
Code
If you know what the whole process looks like, the next process of coding will be simple. I won’t explain too much here, just go to the code:
# -*- 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("清晰度参数异常,仅支持: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())
Conclusion
The code still has room for optimization. I just downloaded the first video in the answer. In theory, there should be more than one answer. A video. If you still have any questions or suggestions, you can communicate with us.
Related learning recommendations: python video tutorial
The above is the detailed content of Learn how to use Python to capture videos with specified answers on Zhihu. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Efficient training of PyTorch models on CentOS systems requires steps, and this article will provide detailed guides. 1. Environment preparation: Python and dependency installation: CentOS system usually preinstalls Python, but the version may be older. It is recommended to use yum or dnf to install Python 3 and upgrade pip: sudoyumupdatepython3 (or sudodnfupdatepython3), pip3install--upgradepip. CUDA and cuDNN (GPU acceleration): If you use NVIDIAGPU, you need to install CUDATool

Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

When selecting a PyTorch version under CentOS, the following key factors need to be considered: 1. CUDA version compatibility GPU support: If you have NVIDIA GPU and want to utilize GPU acceleration, you need to choose PyTorch that supports the corresponding CUDA version. You can view the CUDA version supported by running the nvidia-smi command. CPU version: If you don't have a GPU or don't want to use a GPU, you can choose a CPU version of PyTorch. 2. Python version PyTorch

PyTorch distributed training on CentOS system requires the following steps: PyTorch installation: The premise is that Python and pip are installed in CentOS system. Depending on your CUDA version, get the appropriate installation command from the PyTorch official website. For CPU-only training, you can use the following command: pipinstalltorchtorchvisiontorchaudio If you need GPU support, make sure that the corresponding version of CUDA and cuDNN are installed and use the corresponding PyTorch version for installation. Distributed environment configuration: Distributed training usually requires multiple machines or single-machine multiple GPUs. Place

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.
