-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscrape.py
executable file
·168 lines (112 loc) · 4.4 KB
/
scrape.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
#!/usr/bin/env python3
from bs4 import BeautifulSoup
from datetime import date, datetime, timedelta
import urllib3, time, sys, os, random
from functools import partial
eprint = partial(print, file=sys.stderr)
website = 'http://onlineradiobox.com'
station = 'ro/tananana'
work_dir = os.getenv('HOME') + '/radio/' + station
playlist_dir = os.path.join(work_dir, 'playlist')
tracks_fn = os.path.join(work_dir, 'tracks')
http_pool = urllib3.PoolManager()
def get_url(url):
global http_pool
req = http_pool.request('GET', url, headers = {
'User-agent': 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36',
'Cookie': 'lang=en; cs=ro.radiozu|0; tz=-120; _ouid=55a1d707200646f3; country=ro'})
return req.data
def delay():
r = random.randint(4, 8)
for i in reversed(range(r)):
sys.stderr.write('\r%d... ' % i)
sys.stderr.flush()
time.sleep(1)
sys.stderr.write('\r... ')
sys.stderr.flush()
time.sleep(random.uniform(0, 1))
sys.stderr.write('\r \r')
sys.stderr.flush()
def embed_to_watch(emb):
prefix = 'https://www.youtube.com/embed/'
if not emb.startswith(prefix):
raise Exception('unsupported embed url: ' + emb)
return 'https://www.youtube.com/watch?v=' + emb[len(prefix):]
def get_youtube_url(track):
url = '%s%s' % (website, track)
html = get_url(url)
delay()
soup = BeautifulSoup(html, 'html.parser')
iframe = soup.find('iframe')
return iframe and embed_to_watch(iframe['src']) or 'NOTFOUND'
def download_playlists(d1, d2):
known_tracks_set = set()
if os.path.exists(tracks_fn):
with open(tracks_fn, 'r') as f:
for line in f:
track, youtube, title = line.strip().split(maxsplit=2)
known_tracks_set.add(track)
os.makedirs(playlist_dir, exist_ok=True)
eprint('getting playlists')
for day in range(d1, d2+1):
dt = datetime.now() + timedelta(days=-day)
fn = os.path.join(playlist_dir, dt.strftime('%Y-%m-%d'))
if os.path.exists(fn) and day > 0:
continue
eprint(fn)
url = '%s/%s/playlist/%s' % (website, station, (day and str(day) or ''))
html = get_url(url)
delay()
soup = BeautifulSoup(html, 'html.parser')
links = soup.find_all('a', href=True, attrs={'class': 'ajax'})
tracks = [t for t in links if t['href'].startswith('/track/')]
f = open(fn, 'w')
new = 0
for t in tracks:
href = t['href']
text = t.text.strip()
f.write('%s\t%s\n' % (href, text))
if href not in known_tracks_set:
new += 1
known_tracks_set.add(href)
eprint('found %d tracks, %d new' % (len(tracks), new))
f.close()
def lookup_yt_urls():
known_tracks = {}
if os.path.exists(tracks_fn):
with open(tracks_fn, 'r') as f:
for line in f:
track, youtube, title = line.strip().split(maxsplit=2)
known_tracks[track] = youtube
for fn in os.listdir(playlist_dir):
if fn in ['..', '.']: continue
abs_fn = playlist_dir + '/' + fn
eprint('looking up youtube urls in', abs_fn)
with open(abs_fn, 'r') as f:
lines = f.readlines()
new = 0
for line in lines:
track, title = line.strip().split(maxsplit=1)
if track not in known_tracks:
new += 1
eprint('%d new tracks' % new)
for line in lines:
track, title = line.strip().split(maxsplit=1)
if track not in known_tracks:
eprint('requesting', track, title)
yt_url = get_youtube_url(track)
known_tracks[track] = yt_url
with open(tracks_fn, 'a') as f:
f.write('%s\t%s\t%s\n' % (track, yt_url, title))
eprint(' ', yt_url)
if __name__ == "__main__":
d1 = 1
d2 = 7
if len(sys.argv) == 3:
d1 = int(sys.argv[1])
d2 = int(sys.argv[2])
elif len(sys.argv) != 1:
eprint('syntax: scrape.py d1 d2 (e.g. 1 7)')
sys.exit(1)
download_playlists(d1, d2)
lookup_yt_urls()