-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathDownloadFacebookVideo.py
189 lines (153 loc) · 5.41 KB
/
DownloadFacebookVideo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# coding: utf-8
# https://gist.githubusercontent.com/henryaukc/6fd00b8baee4c069a2b44e574829469f/raw/8424c66008b5105be10abcaf42804a370541f1af/DownloadFacebookVideo.py
# https://forum.omz-software.com/topic/3636/how-to-login-facebook-with-request-module-for-further-access
import webbrowser, os, requests, re, bs4
import appex
import console
import dialogs
data_dir = os.path.join(os.path.abspath('.'),'Videos')
if not os.path.isdir (data_dir):
#print(data_dir)
os.makedirs(data_dir)
os.chdir(data_dir)
#ßprint(os.path.abspath('.'))
def download_file(url, tmpfile=None):
if not tmpfile:
local_filename = url.split('/')[-1]
else:
local_filename = tmpfile
with open(local_filename, 'wb') as f:
r = requests.get(url, stream=True)
total_length = r.headers.get('content-length')
if not total_length:
f.write(r.content)
else:
dl = 0
total_length = float(total_length)
for chunk in r.iter_content(1024):
dl += len(chunk)
f.write(chunk)
return local_filename
def DownloadFile(url, filename):
res = requests.get(url)
try:
res.raise_for_status()
except Exception as exc:
print('There was a problem: %s' % (exc))
with open(filename, "wb") as code:
code.write(res.content)
'''' playFile = open(filename, 'wb')
for chunk in res.iter_content(100000):
playFile.write(chunk)
print('Writing 100000 bytes')
playFile.close()
'''
def OpenURL(url):
res = requests.get(url)
res.encoding = 'utf-8' # 中文顯示必用
try:
res.raise_for_status()
except Exception as exc:
print('There was a problem: %s' % (exc))
return res
def DownloadFacebookVideo(url):
title_length = 50
r = OpenURL(url)
doc = r.text
#print(doc)
soup = bs4.BeautifulSoup(doc, 'html5lib')
#elements = soup.find_all('div', attrs={class: '_5pbx userContent'})
elements = soup.find_all(class_ = '_5pcq')
#print('Elements:' + str(elements))
video_list = []
title_list = []
for i in range(len(elements)): # Search all the posts which contains video
#print (str(elements[i]['href']))
r1 = (re.search(r'videos/(\d+)/', str(elements[i]['href'])))
if not r1:
# Skipped all posts without video
continue
video_id = r1.group(1)
#print (video_id)
x = elements[i].findNext('p')
t = x.getText() # Get the text of the post which contains video
if len(t) > title_length:
t = t[0:title_length] + '...'
temp_dict = {'text': t, 'video_id': video_id, 'hd_src': None, 'sd_src': None, 'sd_src_no_ratelimit':None, 'hd_src_no_ratelimit': None}
video_list.append(temp_dict)
title_list.append(t)
#print(len(video_list))
for i in range(len(video_list)):
video_id = video_list[i]['video_id']
#print ('video_id: ' + video_id)
patt = r'\[\{"is_hds":(?:false|true),"video_id":"' + video_id + '".*?"sd_src_no_ratelimit":"(.*?)".*?"hd_src_no_ratelimit":"(.*?)".*?"hd_src":"(.*?)".*?"sd_src":"(.*?)".*?\}\]'
r2 = re.search(patt, doc)
if r2.group(1) != '':
video_list[i]['sd_src_no_ratelimit'] = r2.group(1).replace('\/','/')
if r2.group(2) != '':
video_list[i]['hd_src_no_ratelimit'] = r2.group(2).replace('\/','/')
if r2.group(3) != '':
video_list[i]['hd_src'] = r2.group(3).replace('\/','/')
if r2.group(4) != '':
video_list[i]['sd_src'] = r2.group(4).replace('\/','/')
# print(video_list)
for i in range(len(video_list)):
t = video_list[i]['text']
if video_list[i]['hd_src'] != None:
url = video_list[i]['hd_src']
video_quality = 'hd_src'
elif video_list[i]['hd_src_no_ratelimit'] != None:
url = video_list[i]['hd_src_no_ratelimit']
video_quality = 'hd_src_no_ratelimit'
elif video_list[i]['sd_src_no_ratelimit'] != None:
url = video_list[i]['sd_src_no_ratelimit']
video_quality = 'sd_src_no_ratelimit'
elif video_list[i]['sd_src'] != None:
url = video_list[i]['sd_src']
video_quality = 'sd_src'
else:
video_quality = None
print('No video found!!')
item = dialogs.list_dialog('Pick', title_list)
if item != None:
for i, text in enumerate(title_list):
if item == text:
vq_list = {}
if video_list[i]['hd_src'] != None:
vq_list['hd_src'] = video_list[i]['hd_src']
if video_list[i]['hd_src_no_ratelimit'] != None:
vq_list['hd_src_no_ratelimit'] = video_list[i]['hd_src_no_ratelimit']
if video_list[i]['sd_src'] != None:
vq_list['sd_src'] = video_list[i]['sd_src']
if video_list[i]['sd_src_no_ratelimit'] != None:
vq_list['sd_src_no_ratelimit'] = video_list[i]['sd_src_no_ratelimit']
video_quality = dialogs.list_dialog('Pick the Video Quality', sorted(vq_list.keys()))
if video_quality != None:
fname = (video_list[i]['text'])[0:20] + '(' + video_quality +').mp4'
#console.set_color(0,0,255)
#print('URL:' + vq_list[video_quality])
print ('Downloading ""' + fname + '"...')
#console.hud_alert('Downloading ""' + fname + '"...')
download_file(vq_list[video_quality], fname)
#DownloadFile(vq_list[video_quality], fname) #(not working in some cases)
console.hud_alert('Done!')
return fname
else:
return None
else:
return None
def main():
if not appex.is_running_extension():
print('This script is intended to be run from the sharing extension.')
return
url = appex.get_url()
if not url:
print('No input URL found.')
return
#url = 'https://www.facebook.com/Spurs/?ref=ts&fref=ts'
fname = DownloadFacebookVideo(url)
if fname != None:
console.quicklook(fname)
os.remove(fname)
if __name__ == '__main__':
main()