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 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Biblioteka dla NK pod Pythona.
BY d33tah, LICENSED UNDER WTFPL.
"""
import json
import mechanize
from lxml import html
nklink = "http://nasza-klasa.pl"
def t(obj): return obj.text_content()
class NK_profile_shout:
def __init__(self,contents='',datetime=''):
self.contents = contents
self.datetime = datetime
def __repr__(self):
pass
class NK_profile:
"""
NK_profile - carries information about people profiles.
"""
def __init__(self,name='',location='',url='',friends_count='',age='',nick='',sex='',shouts = []):
self.name = name
self.location = location
self.url = url
self.friends_count = friends_count
self.uid = url[url.rfind('/')+1:]
self.age = age
self.nick = nick
self.sex = sex
self.shouts = shouts
def __repr__(self):
return "<NK_profile: %s, %s>" % (unicode(self.name),unicode(self.location))
def __eq__(obj1,obj2):
if isinstance(obj1,NK_profile) and isinstance(obj2,NK_profile):
return obj1.name == obj2.name \
and obj1.location == obj2.location \
and obj1.url == obj2.url \
and obj1.friends == obj2.friends \
and obj1.url == obj2.url
@classmethod
def from_html(cls,raw_html):
tree = html.fromstring(raw_html)
data = tree.xpath('//table [@class="profile_info_box"]'+ \
'//td [contains(@class, "content")]')
shouts = []
shouts_tree = tree.xpath('//div [@id="comments"]//table [@class="comment_table"]')
for shout in shouts_tree:
contents = t(shout.find_class('comment_content')[0])
datetime = t(shout.find_class('datetime')[0])
shouts.append(NK_profile_shout(contents=contents,datetime=datetime))
return NK_profile ( name=t(data[0])+' '+t(data[2]),
location=t(data[1]),
age=t(data[3]).strip(' lat'),
nick=t(data[4]),
sex=t(data[5]),
shouts=shouts,
#phone=t(data[7])
)
class NK_forum_post:
"""
NK_forum_post - carries information about a specific thread post.
"""
def __init__(self,date,contents,author):
self.date = date
self.contents = contents
self.author = author
def __repr__(self):
return unicode("<NK_forum_post: %s, %s>" % (self.date, self.author))
class NK_forum_thread:
"""
NK_forum_thread - carries information about a specific froum thread.
"""
def __init__(
self,
title,
url,
started_author,
started_time,
posts_count,
lastpost_summary,
lastpost_author,
lastpost_date):
self.title = title
self.url = url
self.started_author = started_author
self.started_time = started_time
self.posts_count = posts_count
self.lastpost_summary = lastpost_summary
self.lastpost_author = lastpost_author
self.lastpost_date = lastpost_date
def __repr__(self):
return unicode("<NK_forum_thread: %s, %s [%s]>" % (
self.title.encode('utf-8'),
self.url.replace(nklink,''),
self.posts_count))
class NK_forum:
"""
NK_forum - carries information about a specific forum
"""
def __init__(self,url,school_name=''):
self.url = url
self.school_name = school_name
def __repr__(self):
return unicode("<NK_forum: %s>" % self.school_name)
class PyNK:
"""
PyNK - Nasza-Klasa Python API.
"""
def browser_setup(self):
"""
browser_setup(self) - prepares WWW::Mechanize environment
"""
self.br = mechanize.Browser()
user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; ' + \
'Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)'
self.br.addheaders = [("User-agent",user_agent)]
self.br.set_handle_robots(False)
#self.br.viewing_html=lambda: True
def __init__ (self,username,password,auth_cookie=""):
self.browser_setup()
self.br.open(nklink)
self.br.select_form(nr=0)
self.br.form["login"]=username
self.br.form["password"]=password
self.br.submit()
dashboard_html = self.br.response().read()
if dashboard_html.find('Witaj') == -1:
raise Exception('Blad logowania, zle haslo?')
self.basic_auth = self.br._ua_handlers['_cookies'].cookiejar._cookies[
".nk.pl"]["/"]["basic_auth"].value
self.dashboard_tree = html.fromstring(dashboard_html)
def get_my_profile(self):
"""
get_my_profile(self) - fetches information about logged in user
from his dashboard
"""
box = self.dashboard_tree.xpath('//div[contains(@class,"profile_box")]')
return NK_profile(
name = t(box[0][1][0][1][1][0][0]),
location = t(box[0][1][0][1][1][0][1]),
url = nklink+box[0][1][0][1][1][0][0].values()[2],
friends_count =t(box[0][1][0][0][2])
)
def get_my_watched_forums(self, unread_only=False):
"""
get_my_watched_forums(self, unread_only=False) - extracts information
about logged in user's watched forums.
"""
ret = []
for entry in self.dashboard_tree.xpath('//ul [@id="forum_max"]//li'):
if not unread_only or not entry[0].items()[0][1].find('unread'):
ret.append(NK_forum(school_name = t(entry[1]),
url = nklink+entry[1].items()[1][1]))
return ret
def get_forum_threads(self,forum):
"""
get_forum_threads(self,forum) - fetches a list of threads in a specified
forum
"""
ret = []; page = 1
self.br.open(forum.url)
while 1:
forum_tree = html.fromstring(self.br.response().read())
threads = forum_tree.xpath('//div [@id="threads"]//tr')[1:]
if len(threads) > 1:
for thread in threads:
if thread.text_content() == " ":
continue
try: #wychrzania sie jesli posty=0 (http://tnij.org/g0un)
ret.append(NK_forum_thread(
title = t(thread[0][1][0]),
url = nklink+thread[0][1][0].items()[0][1][1:],
started_author = t(thread[1][0]),
started_time = t(thread[1][1]),
posts_count = int(t(thread[2])),
lastpost_summary = t(thread[3][0][0][0]),
lastpost_author = t(thread[3][0][0][2]),
lastpost_date = t(thread[3][0][0][3])
))
except: pass
nextpage = forum_tree.xpath('//a [contains(@title, "pna")]')
if not nextpage:
break
self.br.open(nklink+nextpage[0].items()[3][1])
return ret
def get_thread_posts(self,thread):
"""
get_thread_posts(self,thread) - fetches a list of posts in a specified
thread
"""
ret = []
self.br.open(thread.url)
while 1:
thread_tree = html.fromstring(self.br.response().read())
posts = thread_tree.xpath('//div [@class="post"]')
for post in posts:
ret.append(NK_forum_post(
date = post[0].text_content(),
contents = post[1][1].text_content(),
author = NK_profile(
name = t(post[1][2][0][1][0]),
location = t(post[1][2][0][1][1]),
url = nklink+post[1][2][0][1].items()[2][1],
friends_count =t(post[1][2][0][2])
)
))
nextpage = thread_tree.xpath('//a [contains(@title, "pna")]')
if not nextpage:
break
self.br.open(nklink+nextpage[0].items()[3][1])
return ret
def get_friends(self,profile):
ret = []
json_url = 'http://nk.pl/friends_list/%s/575/0/0?t=%s' % (
profile.uid,self.basic_auth)
try:
json_data = json.loads(self.br.open(json_url).read()[3:])
except:
print "Uzytkownik prawdopodobnie usuniety, pomijam..."
return ret
i=0
while 1:
if i==len(json_data["UID"]):
break
ret.append(NK_profile(
name = "%s %s" % (json_data["FIRST_NAME"][i],json_data["LAST_NAME"][i]),
location = json_data["CITY"][i],
url = "%s/profile/%s" % (nklink,json_data["UID"][i]),
friends_count =json_data["FRIENDS_COUNT"][i]
))
i+=1
return ret
"""
SELF-TEST PART FOLLOWS...
"""
if __name__ == '__main__':
from config import *
print "Logowanie...",
nk = PyNK(login,password)
print "gotowe."
print "Otrzymalismy basic_auth=%s" % nk.basic_auth
my_friends = nk.get_friends(nk.get_my_profile())
"""
for first in my_friends:
print '\nSprawdzam wspolnych znajomych z %s...' % first.name
first_friends = nk.get_friends(first)
for second in first_friends:
if second in my_friends:
print second.name
"""
for friend in my_friends:
print "Przetwarzam "+friend.name
friend = NK_profile.from_html(nk.br.open(friend.url).read())
for shout in friend.shouts:
if shout.contents.lower().find('najlepszego')!=-1:
print "Znaleziono dnia "+shout.datetime.split(' ')[0]
"""
watched_forums = nk.get_my_watched_forums()
for forum in watched_forums:
threads = nk.get_forum_threads(forum)
for thread in threads:
if thread.posts_count < 2:
continue
print "Wybralem watek: %s" % thread
posts = nk.get_thread_posts(thread)
print "Znalazlem postow: %s" % len(posts)
raise Exception('Wszystko ok')
"""
|