Amazing-Python-Scripts

Форк
0
138 строк · 3.2 Кб
1
# ALL Imports
2

3
import tkinter as tk
4
import requests as req
5
import html
6
import time
7
from tkinter.ttk import *
8
from threading import Thread
9
import queue
10
from queue import Empty
11

12

13
def Invalid_Url():
14
    """ Sets Status bar label to error message """
15
    Status["text"] = "Invalid URL..."
16
    Status["fg"] = "red"
17

18

19
def Download_vid():
20

21
    # Validates Link and download Video
22
    global Url_Val
23
    url = Url_Val.get()
24

25
    Status["text"] = "Downloading"
26
    Status["fg"] = "green"
27

28
    # Validating Input
29

30
    if not "linkedin.com/posts" in url:
31
        Invalid_Url()
32
        return
33

34
    response = req.get(url)
35

36
    if not response.status_code == 200:
37
        Invalid_Url()
38
        return
39

40
    htmlsource = response.text
41

42
    sources = html.unescape(htmlsource).split()
43

44
    for source in sources:
45

46
        if "dms.licdn.com" in source:
47

48
            videourl = source.split(',')[0].split('"src":')[1][1:-1]
49
            start_downloading()
50

51
            download_thread = VideoDownload(videourl)
52
            download_thread.start()
53
            monitor(download_thread)
54
            break
55

56

57
class VideoDownload(Thread):
58

59
    def __init__(self, url):
60
        super().__init__()
61

62
        self.url = url
63

64
    def run(self):
65
        """ download video"""
66

67
        # save the picture to a file
68
        block_size = 1024  # 1kB
69
        r = req.get(self.url, stream=True)
70
        total_size = int(r.headers.get("content-length"))
71

72
        with open('video.mp4', 'wb') as file:
73
            totaldata = 0
74
            for data in r.iter_content(block_size):
75
                totaldata += len(data)
76
                per_downloaded = totaldata*100/total_size
77
                queue.put(per_downloaded)
78
                bar['value'] = per_downloaded
79
                file.write(data)
80
                time.sleep(0.01)
81
            file.close()
82
            print("Download Finished")
83

84
        print("Download Complete !!!")
85
        Status["text"] = "Finished!!"
86
        Status["fg"] = "green"
87

88

89
# start download
90
def start_downloading():
91
    bar["value"] = 0
92

93

94
def monitor(download_thread):
95
    """ Monitor the download thread """
96
    if download_thread.is_alive():
97

98
        try:
99
            bar["value"] = queue.get(0)
100
            ld_window.after(10, lambda: monitor(download_thread))
101
        except Empty:
102
            pass
103

104
# GUI
105

106

107
ld_window = tk.Tk()
108
ld_window.title("Linkedin Video Downloader")
109
ld_window.geometry("400x300")
110

111
# Label for URL Input
112
input_label = tk.Label(ld_window, text="Enter Linkedin Video URL:")
113
input_label.pack()
114

115
queue = queue.Queue()
116

117
# Input of URL
118
Url_Val = tk.StringVar()
119
Url_Input = tk.Entry(ld_window, textvariable=Url_Val, font=("Calibri", 9))
120
Url_Input.place(x=25, y=50, width=350)
121

122
# Button for Download
123
Download_button = tk.Button(ld_window, text="Download", font=(
124
    "Calibri", 9), command=Download_vid)
125
Download_button.place(x=100, y=100, width=200)
126

127
# Progress Bar
128
bar = Progressbar(ld_window, length=350,
129
                  style='grey.Horizontal.TProgressbar', mode='determinate')
130
bar.place(y=200, width=350, x=25)
131

132

133
# Text for Status of Downloading
134
Status = tk.Label(ld_window, text="Hello!! :D", fg="blue", font=(
135
    "Calibri", 9), bd=1, relief=tk.SUNKEN, anchor=tk.W, padx=3)
136
Status.pack(side=tk.BOTTOM, fill=tk.X)
137

138
ld_window.mainloop()
139

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.