-
Notifications
You must be signed in to change notification settings - Fork 2
/
weibo.py
210 lines (187 loc) · 6.97 KB
/
weibo.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
import requests
import re
import json
try:
from urlparse import urljoin
from urllib import quote
is_py3k = False
except:
from urllib.parse import urljoin, quote
is_py3k = True
import base64
from hashlib import sha1 as _sha1
def sha1(string):
if is_py3k:
string = string.encode('UTF8')
return _sha1(string).hexdigest()
try:
import cPickle as pickle
except:
import pickle
from bs4 import BeautifulSoup
import os
import db
class Weibo(object):
re_view = re.compile('view\((.+?)\)$')
def __init__(self, email, passwd, cookie_file = "cookies.txt"):
self.email = email
self.passwd = passwd
self.cookie_file = cookie_file
self.browser = requests.session()
self.browser.config['base_headers']['User-Agent'] = 'Mozilla/5.0 (X11; Linux i686; rv:8.0) Gecko/20100101 Firefox/8.0'
self.browser.config['base_headers']['Accept-Charset'] = 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
def set_user_agent(self, agent):
self.browser.config['base_headers']['User-Agent'] = agent
def load_cookies(self):
if os.path.isfile(self.cookie_file):
f = open(self.cookie_file, 'rb')
self.browser.cookies = pickle.load(f)
f.close()
return True
return False
def dump_cookies(self):
f = open(self.cookie_file, 'wb')
pickle.dump(self.browser.cookies, f)
f.close()
def get(self, *args, **kws):
return self.browser.get(*args, **kws)
def post(self, *args, **kws):
return self.browser.post(*args, **kws)
def login(self, pin = None):
prelogin = self.prelogin()
url = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.2)'
data={
'entry': 'weibo',
'gateway': '1',
'from': '',
'savestate': '7',
'userticket': '1',
'vsnf': '1',
'ssosimplelogin': '1',
'su': self.enc_user(),
'service': 'miniblog',
'servertime': prelogin['servertime'],
'nonce': prelogin['nonce'],
'pwencode': 'wsse',
#'rsakv': prelogin['rsakv'],
'sp': self.enc_passwd(prelogin['servertime'], prelogin['nonce']),
'encoding': 'UTF-8',
'prelt': 255,
'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
'returntype': 'META'
}
if pin:
data['pcid'] = pin['pcid']
data['door'] = pin['door']
r = self.post(url, data = data)
p = re.compile('location\.replace\([\'"](.*?)[\'"]\)')
login_url = p.search(r.text).group(1)
r = self.get(login_url)
p = re.compile('\((.+?)\)')
text = r.text
data = p.search(text).group(1)
data = json.loads(data)
if not data['result']:
print(data['reason'])
return self.login(self.get_pin())
return text
def prelogin(self):
url = 'http://login.sina.com.cn/sso/prelogin.php?entry=sso&callback=sinaSSOController.preloginCallBack&su=dW5kZWZpbmVk&rsakt=mod&client=ssologin.js(v1.4.2)&_=1352276350389'
r = self.get(url)
p = re.compile('\((.+?)\)')
json_data = p.search(r.text).group(1)
data = json.loads(json_data)
return data
def enc_user(self):
if is_py3k:
return base64.encodebytes(quote(self.email).encode('UTF8')).strip()
return base64.encodestring(quote(self.email)).strip()
def enc_passwd(self, servertime, nonce):
pwd = sha1(self.passwd)
pwd = sha1(pwd)
pwd = pwd + str(servertime) + str(nonce)
pwd = sha1(pwd)
return pwd
def get_html(self, text, pid):
html = BeautifulSoup(text)
retval = []
for script in html.find_all('script'):
if script:
data = self.re_view.search(script.text.strip())
if data:
data = data.group(1)
data = json.loads(data)
pid1 = data.get('pid')
if not is_py3k:
pid1 = pid1.encode('UTF8')
if pid1 == pid:
retval.append(data.get('html'))
return retval
def parse_user_data(self, html):
cnlist = html.find('ul', {'class': 'cnfList'})
if cnlist:
for fan in cnlist.find_all('li'):
user = {}
data = fan.get('action-data')
if data is None:
continue
for data in fan.get('action-data').split('&'):
data = data.split('=')
if data[0] == 'fnick':
user['nickname'] = data[1]
else:
user[data[0]] = data[1]
info = fan.find('div', {'class': 'info'})
if info:
user['info'] = info.text.strip()
else:
user['info'] = ''
addr = fan.find('div', {'class': 'name'})
if addr and addr.span:
user['address'] = addr.span.text.strip()
else:
user['address'] = ""
face = fan.find('div', {'class': 'face'})
if not db.is_exists(user['uid']) and face and face.img:
user['face'] = self.get(face.img.get('src')).content
else:
user['face'] = b'\x00\x00'
yield user
def get_users(self, url, key, re_href):
followed = []
urls = [url]
while True:
if len(urls) == 0:
break
url = urls.pop()
if url in followed:
continue
followed.append(url)
print('Get data from [%s]'%url)
r = self.get(url)
html = self.get_html(r.text, key)[0]
html = BeautifulSoup(html)
for user in self.parse_user_data(html):
yield user
for a in html.find_all('a', {'href': re_href}):
urls.append(urljoin(r.url, a.get('href')))
def get_myfans(self, uid):
url = 'http://weibo.com/%s/myfans'%uid
re_href = re.compile('/%s/myfans'%uid)
key = 'pl_relation_fans'
return self.get_users(url, key, re_href)
def get_myfollow(self, uid):
url = 'http://weibo.com/%s/myfollow'%uid
re_href = re.compile('/%s/myfollow'%uid)
key = 'pl_relation_myfollow'
return self.get_users(url, key, re_href)
def get_hisfans(self, uid):
url = 'http://weibo.com/%s/fans'%uid
re_href = re.compile('/%s/fans'%uid)
key = 'pl_relation_hisFans'
return self.get_users(url, key, re_href)
def get_hisfollow(self, uid):
url = 'http://weibo.com/%s/follow'%uid
re_href = re.compile('/%s/follow'%uid)
key = 'pl_relation_hisFollow'
return self.get_users(url, key, re_href)