forked from gism/filmaffinity2CSV
-
Notifications
You must be signed in to change notification settings - Fork 0
/
faHelper.py
365 lines (292 loc) · 14.4 KB
/
faHelper.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# -*- coding: utf-8 -*-
import threading, Queue
import sys
import re
import cookielib, urllib, urllib2
from bs4 import BeautifulSoup
WORKERS = 4 # Mutli-Thread workers
# From October 12, 2015 to 20151012
def changeDateString(dateBad):
date = dateBad.split(" ")
date[0] = date[0].replace("January", "01")
date[0] = date[0].replace("February", "02")
date[0] = date[0].replace("March", "03")
date[0] = date[0].replace("April", "04")
date[0] = date[0].replace("May", "05")
date[0] = date[0].replace("June", "06")
date[0] = date[0].replace("July", "07")
date[0] = date[0].replace("August", "08")
date[0] = date[0].replace("September", "09")
date[0] = date[0].replace("October", "10")
date[0] = date[0].replace("November", "11")
date[0] = date[0].replace("December", "12")
date[1] = date[1].replace(",", "")
if len(date[1])==1:
date[1] = "0" + date[1]
dateGood = date[2] + date[0] + date[1]
return dateGood
class FAhelper:
"""Clase para ayudar a bajar la informacion de filmaffinity"""
# FA URL set.
# urlLogin= "http://www.filmaffinity.com/en/login.php"
urlLogin = "https://filmaffinity.com/en/account.ajax.php?action=login" # New login URL? seems it works
urlVotes = "http://www.filmaffinity.com/en/myvotes.php"
urlVotes_prefix = "http://www.filmaffinity.com/en/myvotes.php?p="
urlVotes_sufix = "&orderby="
urlVotesID = "http://www.filmaffinity.com/en/userratings.php?user_id="
urlVotesIDpageSufix = "&p="
urlFilm = "http://www.filmaffinity.com/en/film"
urlFilmSufix = ".html"
urlMain = "http://www.filmaffinity.com/en/main.php"
cookiejar = None
webSession = None
faMovies = []
faMoviesFilled = []
def __init__(self):
self.userName = ""
self.userPass = ""
self.userId = "0"
# Enable cookie support for urllib2
self.cookiejar = cookielib.CookieJar()
self.webSession = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookiejar))
def setUser(self, userName, userPass):
self.userName = userName
self.userPass = userPass
def getUser(self):
return self.userName, self.userPass
def setUserID(self, userId):
self.userId = str(userId)
def login(self):
user, password = self.getUser()
self.webSession.open(self.urlLogin)
# Post data to Filmaffinity login URL.
dataForm = {"postback": 1, "rp": "", "username":user, "password":password} # a 30/10/2015 Han cambiado el formulario de login, que alegria
dataPost = urllib.urlencode(dataForm)
request = urllib2.Request(self.urlLogin, dataPost)
self.webSession.open(request) # Our cookiejar automatically receives the cookies, after the request
webResponse = self.webSession.open(self.urlVotes)
pattern = re.compile ('\?user_id=(\d+)"')
match = pattern.search (webResponse.read())
if match:
userID = match.group(1)
else:
print "ERROR FOUND: change regular expression at login() for user ID. Probably FA changed web page structure"
sys.exit("Error happens, check log.")
self.userId = userID
# returns 1 when login is succeed
def loginSucceed(self):
return len(self.cookiejar) > 1
# returns value of film affinity user ID
def getUserID(self):
return self.userId
def getNumVotes(self):
if self.userId =="0":
print "ERROR FOUND: No user id found. Please login or set user id."
sys.exit("Error happens, check log.")
return
url = self.urlVotesID + self.userId
webResponse = self.webSession.open(url)
html = webResponse.read()
pattern = re.compile ('Page <b>1<\/b> of <b>([\d]+)<\/b>')
match = pattern.search (html)
if match:
numPages = match.group(1)
else:
print "ERROR FOUND: change regular expression at getNumVotes() for numPages. Probably FA changed web page structure"
sys.exit("Error happens, check log.")
pattern = re.compile ('<div class="number">([\d,\.]+)<\/div>[\r\n\s\t]+<div class="text">Votes<\/div>')
match = pattern.search (html)
if match:
numVotes = match.group(1)
else:
print "ERROR FOUND: change regular expression at getVotesByID() for numVotes. Probably FA changed web page structure"
sys.exit("Error happens, check log.")
return numVotes, numPages
def getDumpVotesPage(self, page):
if self.userId =="0":
print "ERROR FOUND: No user id found. Please login or set user id."
sys.exit("Error happens, check log.")
return
url = self.urlVotesID + str(self.userId) + self.urlVotesIDpageSufix + str(page)
webResponse = self.webSession.open(url)
html = webResponse.read()
html = unicode(html, 'utf-8')
soupPage = BeautifulSoup(html, 'html.parser')
daysDiv = soupPage.body.findAll('div', attrs={'class':'user-ratings-wrapper'})
for dayDiv in daysDiv:
# Get day when the vote was done:
day = dayDiv.find('div', attrs={'class':'user-ratings-header'})
dayBadFormat = day.text.replace("Rated on ", "")
dayYYYYMMDD = changeDateString(dayBadFormat)
# Each day may have more than one movie:
rates = dayDiv.findAll('div', attrs={'class':'user-ratings-movie fa-shadow'})
for movie in rates:
movieResult = []
# Get filmaffinity ID
movieID = movie.find('div', attrs={'class':'movie-card movie-card-0'}).get("data-movie-id")
# Get movie rate
movieRate = movie.find('div', attrs={'class':'ur-mr-rat'}).text
# Get title
title = movie.find('div', attrs={'class':'mc-title'})
pattern = re.compile ('\((\d\d\d\d)\)')
match = pattern.search (title.text)
if match:
movieYear = match.group(1)
movieTitle = title.text.replace("(" + movieYear + ")", "").strip()
movieTitle = movieTitle.replace("(TV Series)", "").strip()
movieTitle = movieTitle.replace("(TV)", "").strip()
movieTitle = movieTitle.replace("(S)", "").strip()
else:
print "ERROR FOUND: change regular expression at getDumpVotesPage() for movie year. Probably FA changed web page structure"
sys.exit("Error happens, check log.")
movieResult.append(movieID)
movieResult.append(movieTitle)
movieResult.append(movieYear)
movieResult.append(movieRate)
movieResult.append(dayYYYYMMDD)
# print movieID, movieTitle, movieYear, movieRate, dayYYYYMMDD
self.faMovies.append(movieResult)
def getMovieInfoById(self, movieID):
found = 0
intento = 0
while found == 0:
if intento <3:
url = self.urlFilm + str(movieID) + self.urlFilmSufix
webResponse = self.webSession.open(url)
html = webResponse.read()
html = unicode(html, 'utf-8')
if webResponse.getcode() != 200:
print webResponse.getcode()
# Get movie title information
pattern = re.compile ('<span itemprop="name">([\w\W\s]+?)<\/span>')
match = pattern.search (html)
if match:
movieTitle = match.group(1)
movieTitle = movieTitle.replace("(TV Series)", "").strip()
movieTitle = movieTitle.replace("(TV)", "").strip()
movieTitle = movieTitle.replace("(S)", "").strip()
found = 1
else:
intento = intento + 1
else:
print "ERROR FOUND: change regular expression at getMovieInfoById() for movie title. Probably FA changed web page structure. Movie ID: " + str(movieID)
sys.exit("Error happens, check log.")
# Get movie year information
pattern = re.compile ('<dt>Year<\/dt>[\s\r\n]+<dd[\w\W]+?>(\d\d\d\d)<\/dd>')
match = pattern.search (html)
if match:
movieYear = match.group(1)
else:
print "ERROR FOUND: change regular expression at getMovieInfoById() for movie year. Probably FA changed web page structure. Movie ID: " + str(movieID)
sys.exit("Error happens, check log.")
# Get movie country information
pattern = re.compile ('<dt>Country<\/dt>[\r\n\s]+<dd><span id="country-img"><img src="\/imgs\/countries\/[\w]+.jpg" title="[\W\w\s]+?"><\/span> ([\W\w\s]+?)<\/dd>')
match = pattern.search (html)
if match:
movieCountry = match.group(1)
else:
print "ERROR FOUND: change regular expression at getMovieInfoById() for movie county. Probably FA changed web page structure. Movie ID: " + str(movieID)
sys.exit("Error happens, check log.")
# Get movie director information
pattern = re.compile ('<dt>Director<\/dt>[\w\s\W\r\n]+?<span itemprop="name">([\w\W\s]+?)<\/span>')
match = pattern.search (html)
if match:
movieDirector = match.group(1)
movieDirector = movieDirector.strip()
else:
print "ERROR FOUND: change regular expression at getMovieInfoById() for movie director. Probably FA changed web page structure. Movie ID: " + str(movieID)
sys.exit("Error happens, check log.")
# Get movie cast information
pattern = re.compile ('<dt>Cast<\/dt>[\s\r\n]+?<dd>([\w\W]+?)<\/dd>')
match = pattern.search (html)
if match:
castWithLink = match.group(1)
castWithLink = re.sub('\s?<a href=[\w\W]+?>', "", castWithLink)
movieCast = castWithLink.replace("</a>", "")
movieCast = movieCast.replace("\r\n", " ")
movieCast = movieCast.strip()
else:
print "ERROR FOUND: change regular expression at getMovieInfoById() for movie cast. Probably FA changed web page structure. Movie ID: " + str(movieID)
movieCast = "None"
# Get movie genre infomration
pattern = re.compile ('<dt>Genre<\/dt>[\s\r\n]+?<dd>([\w\W]+?)<\/dd>')
match = pattern.search (html)
if match:
genreWithLink = match.group(1)
genreWithLink = genreWithLink.replace("</span>", "")
genreWithLink = genreWithLink.replace("<span>", "")
genreWithLink = re.sub('\s+?<a href=[\w\W]+?>', "", genreWithLink)
movieGenre = genreWithLink.replace("</a>", "")
movieGenre = movieGenre.replace("\r\n", " ")
movieGenre = movieGenre.strip()
else:
print "ERROR FOUND: change regular expression at getMovieInfoById() for movie genre. Probably FA changed web page structure. Movie ID: " + str(movieID)
sys.exit("Error happens, check log.")
return movieTitle, movieYear, movieCountry, movieDirector, movieCast, movieGenre
def getMoviesDumped(self):
return self.faMovies
def getFilledMoviesDumped(self):
return self.faMoviesFilled
def getDumpAllVotes(self):
numVotes, numPages = self.getNumVotes()
print ("FOUND: {0} movies in {1} pages." .format (numVotes,numPages))
queue = Queue.Queue()
for i in range(WORKERS):
# FaVoteDumper(queue, self).start() # start a worker
worker = FaVoteDumper(queue, self)
worker.setDaemon(True)
worker.start()
for page in range(1, int(numPages) + 1):
queue.put(page)
print "All pages pushed to queue!"
for i in range(WORKERS):
queue.put(None) # add end-of-queue markers
# Wait all threats of queue to finish
queue.join()
queueFill = Queue.Queue()
for i in range(WORKERS):
#FaFillInfo(queueFill, self).start() # start a worker
worker = FaFillInfo(queueFill, self)
worker.setDaemon(True)
worker.start()
for movie in self.faMovies:
# print "Push movie: ", movie[0]
queueFill.put(movie)
print "\r\nAll movies pushed to queue to get all movie information."
for i in range(WORKERS):
queueFill.put(None) # add end-of-queue markers
# Wait all threats of queueFill to finish
queueFill.join()
class FaVoteDumper(threading.Thread):
def __init__(self, queue, faHelp):
self.__queue = queue
threading.Thread.__init__(self)
self.faHelp = faHelp
def run(self):
while 1:
page = self.__queue.get()
if page is None:
self.__queue.task_done()
break # reached end of queue
self.faHelp.getDumpVotesPage(page)
print "Analyzing vote page: ", page
self.__queue.task_done()
class FaFillInfo(threading.Thread):
def __init__(self, queue, faHelp):
self.__queue = queue
threading.Thread.__init__(self)
self.faHelp = faHelp
def run(self):
while 1:
film = self.__queue.get()
if film is None:
self.__queue.task_done()
break # reached end of queue
extraInfo = self.faHelp.getMovieInfoById(film[0]) # movieTitle, movieYear, movieCountry, movieDirector, movieCast, movieGenre
film.append(extraInfo[2])
film.append(extraInfo[3])
film.append(extraInfo[4])
film.append(extraInfo[5])
self.faHelp.faMoviesFilled.append(film)
print "[FA get all data] ", film[1]
self.__queue.task_done()