Amazing-Python-Scripts
108 строк · 3.5 Кб
1import requests2from bs4 import BeautifulSoup3import json4
5
6class Video:7"""8Create an instance of `Video` class.
9```python
10video = Video(video_url="video_url")
11```
12
13| Methods | Details |
14| --------------- | ------------------------ |
15| `.getDetails()` | Return the video details |
16"""
17
18def __init__(self, video_url):19self.video_url = video_url20
21def getDetails(self):22"""23Class - `Video`
24Example:
25```
26video_data = Video("https://www.youtube.com/watch?v=pBy1zgt0XPc")
27video_data.getDetails()
28```
29Returns:
30{
31"title": Tile of the video
32"description": Description of the video
33"views_count": No. of views of the video,
34"upload_date": Upload date of the video,
35"comment_count": No. of comments,
36"channel_name": Name of the channel,
37"channel_avatar": Channel avatar,
38"subscriber_count": No. of channel subscribers,
39"channel_url": Link to the channel
40}
41"""
42url = self.video_url43try:44res = requests.get(url)45soup = BeautifulSoup(res.text, "html.parser")46video_data = {"video_data": []}47
48scripts = soup.find_all("script")49req_script = scripts[44].text.strip()50script = req_script[20:-1]51data = json.loads(script)52
53base = data["contents"]["twoColumnWatchNextResults"]["results"]["results"][54"contents"55]56
57first = base[0]["videoPrimaryInfoRenderer"]58title = (59first["title"]["runs"][0]["text"]60.strip()61.encode("ascii", "ignore")62.decode()63)64views = first["viewCount"]["videoViewCountRenderer"]["viewCount"][65"simpleText"66]67date = first["dateText"]["simpleText"]68
69channel_data = base[1]["videoSecondaryInfoRenderer"]["owner"][70"videoOwnerRenderer"71]72avatar = channel_data["thumbnail"]["thumbnails"][2]["url"]73name = channel_data["title"]["runs"][0]["text"]74channel_url = channel_data["title"]["runs"][0]["navigationEndpoint"][75"commandMetadata"76]["webCommandMetadata"]["url"]77subs = channel_data["subscriberCountText"]["accessibility"][78"accessibilityData"79]["label"]80
81desc = (82base[1]["videoSecondaryInfoRenderer"]["attributedDescription"][83"content"84]85.strip()86.encode("ascii", "ignore")87.decode()88)89comment_count = base[2]["itemSectionRenderer"]["contents"][0][90"commentsEntryPointHeaderRenderer"91]["commentCount"]["simpleText"]92
93video_data["video_data"].append(94{95"title": title,96"description": desc[:200] + "...",97"views_count": views,98"upload_date": date,99"comment_count": comment_count,100"channel_name": name,101"channel_avatar": avatar,102"subscriber_count": subs,103"channel_url": "https://youtube.com" + channel_url,104}105)106return video_data107except:108return None109