forked from jensb89/OTR-file-rename-for-tv-shows
/
Fernsehserien_de_Scraper.py
215 lines (159 loc) · 7.38 KB
/
Fernsehserien_de_Scraper.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
OTR file rename for tv-shows
Extract all date, time, season and episode information for a specific TV-Show from fernsehserien.de
@author: Jens
"""
from bs4 import BeautifulSoup
from urllib import urlopen
from math import fmod
import re
from types import *
import os
from tv_shows_db import serieslinks
from tv_stations_db import senderlinks
import time
import codecs
class Fernsehserien_de_Scraper(object):
# Parse the EpisodeGuide Page from Fernsehserien.de - get back all episodes as a list
CACHE_FOLDER = '.cache'
def __init__(self, show):
self.name = show #e.g. 'Die Simpsons'
###### DOWNLOADING WEBPAGE : Fernsehserien - EpisodeGuide ########
def downloadWebpage(self):
print 'Trying to get website information...please wait...'
cache = Fernsehserien_de_Scraper.CACHE_FOLDER + '/' + self.name + '_' + 'eplist.dat'
if os.path.isfile(cache) and (time.time() - os.path.getmtime(cache)) < 43200:
print "Use local file..."
webpage = urlopen(cache)
else:
if serieslinks.has_key(self.name):
title = serieslinks[self.name]
else:
title = self.name.replace(' ','-')
webpage = urlopen('http://www.fernsehserien.de/'+title+'/episodenguide').read()
if not(os.path.isdir(self.name.replace('-',' '))):
os.mkdir(self.name.replace('-',' '))
if not(os.path.isdir(Fernsehserien_de_Scraper.CACHE_FOLDER)):
os.mkdir(Fernsehserien_de_Scraper.CACHE_FOLDER)
f = open(cache,'w')
f.write(webpage)
f.close()
print 'Website successfully scraped'
self.soupobj = BeautifulSoup(webpage, "html.parser")
#print self.soupobj.prettify()
def getTitlesGerman(self):
episodetitlesger = self.soupobj.select("td.episodenliste-titel")
for i in episodetitlesger:
if type(i.find('span')) is not NoneType:
i.find('span').decompose()
return [x.text for x in episodetitlesger]
def getTitles(self):
episodetitles = self.soupobj.select("td.episodenliste-originaltitel")
return [x.text for x in episodetitles]
def getDate(self):
episodedate = self.soupobj.select("td.episodenliste-oea")
return [x.text.rstrip('\r\n') for x in episodedate]
def getDateGerman(self):
episodedate = self.soupobj.select("td.episodenliste-ea")
for i in episodedate:
if type(i.find('span')) is not NoneType:
i.find('span').decompose()
return [x.text for x in episodedate]
def getSeasonNumber(self):
episodenumber = self.soupobj.select("td.episodenliste-episodennummer span")
return [episodenumber[2*i].text.replace('.','') for i in range(0,len(episodenumber)/2)]
def getEpisodeNumber(self):
episodenumber = self.soupobj.select("td.episodenliste-episodennummer span")
return [episodenumber[2*i+1].text.replace('.','') for i in range(0,len(episodenumber)/2)]
def getCountEpisode(self):
return len(self.soupobj.select('td.episodenliste-originaltitel'))
def getEpisodeGuide(self, lang = 'de', printout = False):
self.downloadWebpage()
s = self.getSeasonNumber()
e = self.getEpisodeNumber()
if lang == 'de':
d, t = self.getDateGerman(), self.getTitlesGerman()
else:
d, t = self.getDate(), self.getTitles()
#print len(getTitles(soup))
if printout:
for i in range(0,self.getCountEpisode()):
print 'S' + s[i] + '.' + 'E'+ e[i] + ' : ' + t[i].decode('utf-8') + '( ' + d[i] + ' )'
return (d,s,e,t)
###### DOWNLOADING WEBPAGE : Fernsehserien - TimeTable ########
def getTimeTable(self, sender):
print 'Trying to get timetable information...please wait...'
if senderlinks.has_key(sender):
senderlink = senderlinks[sender]
else:
print 'Link zu Sender ' + sender +' nicht gefunden'
return 0
cache = Fernsehserien_de_Scraper.CACHE_FOLDER + '/' + self.name + '_ttlist.dat'
if os.path.isfile(cache) and (time.time() - os.path.getmtime(cache)) < 43200:
print "Use local file..."
webpage = urlopen(cache)
else:
if serieslinks.has_key(self.name.replace(' ','-')):
title = serieslinks[self.name.replace(' ','-')]
else:
title = self.name.replace(' ','-')
webpage = urlopen('http://www.fernsehserien.de/'+title+'/sendetermine/'+senderlink+'/-1').read()
if not(os.path.isdir(self.name)):
os.mkdir(self.name)
if not(os.path.isdir(Fernsehserien_de_Scraper.CACHE_FOLDER)):
os.mkdir(Fernsehserien_de_Scraper.CACHE_FOLDER)
f = open(cache,'w')
f.write(webpage)
f.close()
print 'Website successfully scraped'
#soup = BeautifulSoup(fernsehserien_testdata.gethtmlo(), "html.parser")
soup = BeautifulSoup(webpage, "html.parser")
tddata = soup.select("tr")
epdate, eptime, season, episode, title = [],[],[],[],[]
for index, item in enumerate(tddata):
if fmod(index,2) != 0 and index>0:
#print item.text
m = re.search("(\d{2}\.\d{2}\.\d{4}).*?(\d{2}:\d{2}).*?>(\d{1,3})<.*?>(\d{1,2}).*?>(\d{1,2}).*?>([^<]+)", str(item))
if type(m) is not NoneType:
epdate.append(m.group(1))
eptime.append(m.group(2))
season.append(m.group(4))
episode.append(m.group(5))
title.append(m.group(6))
return (epdate, season, episode, title, eptime)
# WINDOWS: DEAL with special chars
import sys
"""
Deal with Windows Output/ Codecs (see http://stackoverflow.com/questions/5419/python-unicode-and-the-windows-console for more info)
"""
reload(sys)
sys.setdefaultencoding('utf-8')
#print sys.getdefaultencoding()
if sys.platform == 'win32':
try:
import win32console
except:
print "Python Win32 Extensions module is required.\n You can download it from https://sourceforge.net/projects/pywin32/ (x86 and x64 builds are available)\n"
exit(-1)
# win32console implementation of SetConsoleCP does not return a value
# CP_UTF8 = 65001
win32console.SetConsoleCP(65001)
if (win32console.GetConsoleCP() != 65001):
raise Exception ("Cannot set console codepage to 65001 (UTF-8)")
win32console.SetConsoleOutputCP(65001)
if (win32console.GetConsoleOutputCP() != 65001):
raise Exception ("Cannot set console output codepage to 65001 (UTF-8)")
#import sys, codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
"""
//END
"""
if __name__ == '__main__':
#Print episodeguide
if len(sys.argv)>2:
seriesname = sys.argv[1]
lang = sys.argv[2] #de / us
Fernsehserien_de_Scraper(seriesname).getEpisodeGuide(lang = lang, printout = True)