-
Notifications
You must be signed in to change notification settings - Fork 6
/
myweibo.py
265 lines (244 loc) · 10.8 KB
/
myweibo.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
import base64
import binascii
import httplib2
import json
import logging
import re
import random
import time
import urllib
import requests
import rsa
import pymysql
import urllib.parse
from weibo import Client
connection = pymysql.connect(host="119.23.46.71", user="root", passwd="helloroot", db="myblog", port=3306,
charset="utf8")
cur = connection.cursor()
APP_KEY = '415390189'
APP_SECRET = '958ea2c93dcad4ab45a99098b44b016a'
REDIRECT_URI = 'https://api.weibo.com/oauth2/authorize'
client = Client(APP_KEY, APP_SECRET, REDIRECT_URI)
url = client.authorize_url
'https://api.weibo.com/oauth2/authorize?client_id=415390189&response_type=code&redirect_uri=958ea2c93dcad4ab45a99098b44b016a'
class AppClient:
def __init__(self):
self._appKey = APP_KEY # your app key
self._appSecret = APP_SECRET # your app secret
self._callbackUrl = REDIRECT_URI # your callback url
self._account = '[email protected]' # your weibo user name (eg.email)
self._password = 'wenzhihuai2018.' # your weibo pwd
self.AppCli = client
self._author_url = self.AppCli.authorize_url
def insert(self, user_id, name, location, url, text, created_at, type):
try:
ddd = time.mktime(time.strptime(created_at, "%a %b %d %H:%M:%S +0800 %Y"))
created_at = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ddd))
if len(text) > 1000:
return
text=pymysql.escape_string(text)
print(text)
insert_sql = """insert into myblog.weibo(uid,`name`,location,url,text,created_at,`type`) VALUES (%s,%s,%s,%s,%s,%s,%s)"""
cur.execute(insert_sql, (user_id, name, location, url, text, created_at, int(type)))
connection.commit()
except Exception as e:
print(e)
def get_code(self, session): # 使用该函数避免了手动输入code,实现了模拟用户授权后获得code的功能
conn = httplib2.HTTPSConnectionWithTimeout('api.weibo.com')
postdict = {"client_id": self._appKey,
"redirect_uri": self._callbackUrl,
"userId": self._account,
"passwd": self._password,
"isLoginSina": "0",
"action": "submit",
"response_type": "code",
}
postdata = urllib.parse.urlencode(postdict)
session.headers.update(
{"Referer": self._author_url,
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
}
)
res = session.post('https://api.weibo.com/oauth2/authorize', postdata)
location = res.url
code = location.split('=')[1]
conn.close()
return code
def getAuthorization(self, session): # 将上面函数获得的code再发送给新浪认证服务器,返回给客户端access_token和expires_in,有了这两个东西,咱就可以调用api了
code = self.get_code(session)
self.AppCli.set_code(code)
uuid = self.AppCli.uid
mid_list = []
first_str = client.post('statuses/share',
status=str(random.randrange(1000000)) + 'aafirefst,http://www.cnblogs.com/')
first_weibo = json.dumps(first_str)
first_weibo = json.loads(first_weibo)
mid_list.append(first_weibo['mid'])
time.sleep(5)
second_str = client.post('statuses/share',
status=str(random.randrange(1000000)) + 'aasecfweond,http://www.cnblogs.com/')
second_weibo = json.dumps(second_str)
second_weibo = json.loads(second_weibo)
mid_list.append(second_weibo['mid'])
time.sleep(5)
third_str = client.post('statuses/share',
status=str(random.randrange(1000000)) + 'aathigerd,http://www.cnblogs.com/')
third_weibo = json.dumps(third_str)
third_weibo = json.loads(third_weibo)
mid_list.append(third_weibo['mid'])
time.sleep(5)
logging.info(mid_list)
# 抓取公共微博
count_temp = 1
while (True):
json_str = client.get('statuses/public_timeline', uid=uuid, separators=(',', ':'), count=200)
time.sleep(5)
count_temp = count_temp + 1
if count_temp > 2:
break
d = json.dumps(json_str)
s = json.loads(d)
length = len(s['statuses'])
for i in range(0, length):
try:
data = s['statuses'][i]
#链接中带有链接,无法处理,强制去掉url中的“/“
weibonlp = "http://127.0.0.1:5000/hello/" + urllib.parse.quote_plus(data['text'].replace("/", ""))
logging.info(weibonlp)
type = requests.get(weibonlp).content
self.insert(data['id'], data['user']['name'], data['user']['location'], data['user']['url'],
data['text'], data['created_at'], type)
except Exception as e:
print(e)
return mid_list
class WeiBoLogin(object):
def __init__(self):
self.user_name = None
self.pass_word = None
self.user_uniqueid = None
self.user_nick = None
self.session = requests.Session()
self.session.headers.update(
{"User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0"})
self.session.get("http://weibo.com/login.php")
return
def login(self, user_name, pass_word):
self.user_name = user_name
self.pass_word = pass_word
self.user_uniqueid = None
self.user_nick = None
# get json data
s_user_name = self.get_username()
json_data = self.get_json_data(su_value=s_user_name)
if not json_data:
return False
s_pass_word = self.get_password(json_data["servertime"], json_data["nonce"], json_data["pubkey"])
# make post_data
post_data = {
"entry": "weibo",
"gateway": "1",
"from": "",
"savestate": "7",
"userticket": "1",
"vsnf": "1",
"service": "miniblog",
"encoding": "UTF-8",
"pwencode": "rsa2",
"sr": "1280*800",
"prelt": "529",
"url": "http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack",
"rsakv": json_data["rsakv"],
"servertime": json_data["servertime"],
"nonce": json_data["nonce"],
"su": s_user_name,
"sp": s_pass_word,
"returntype": "TEXT",
}
# get captcha code
if json_data["showpin"] == 1:
url = "http://login.sina.com.cn/cgi/pin.php?r=%d&s=0&p=%s" % (int(time.time()), json_data["pcid"])
with open("captcha.jpeg", "wb") as file_out:
file_out.write(self.session.get(url).content)
code = input("请输入验证码:")
post_data["pcid"] = json_data["pcid"]
post_data["door"] = code
# login weibo.com
login_url_1 = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)&_=%d" % int(time.time())
json_data_1 = self.session.post(login_url_1, data=post_data).json()
if json_data_1["retcode"] == "0":
params = {
"callback": "sinaSSOController.callbackLoginStatus",
"client": "ssologin.js(v1.4.18)",
"ticket": json_data_1["ticket"],
"ssosavestate": int(time.time()),
"_": int(time.time() * 1000),
}
response = self.session.get("https://passport.weibo.com/wbsso/login", params=params)
json_data_2 = json.loads(re.search(r"\((?P<result>.*)\)", response.text).group("result"))
if json_data_2["result"] is True:
self.user_uniqueid = json_data_2["userinfo"]["uniqueid"]
self.user_nick = json_data_2["userinfo"]["displayname"]
else:
logging.warning("WeiBoLogin failed: %s", json_data_2)
app = AppClient()
mid_list = app.getAuthorization(self.session)
# delete a weibo
self.session.headers.update(
{"Referer": "http://weibo.com/1925306000/profile?topnav=1&wvr=6&is_all=1",
"host": "weibo.com",
"Origin": "http://weibo.com"}
)
for mid in mid_list:
data_for_del = {
"mid": mid,
}
rep = self.session.post('http://weibo.com/aj/mblog/del', data=data_for_del)
logging.info(mid)
else:
logging.warning("WeiBoLogin failed: %s", json_data_1)
return True if self.user_uniqueid and self.user_nick else False
def get_username(self):
"""
get legal username
"""
username_quote = urllib.parse.quote_plus(self.user_name)
username_base64 = base64.b64encode(username_quote.encode("utf-8"))
return username_base64.decode("utf-8")
def get_json_data(self, su_value):
"""
get the value of "servertime", "nonce", "pubkey", "rsakv" and "showpin", etc
"""
params = {
"entry": "weibo",
"callback": "sinaSSOController.preloginCallBack",
"rsakt": "mod",
"checkpin": "1",
"client": "ssologin.js(v1.4.18)",
"su": su_value,
"_": int(time.time() * 1000),
}
try:
response = self.session.get("http://login.sina.com.cn/sso/prelogin.php", params=params)
json_data = json.loads(re.search(r"\((?P<data>.*)\)", response.text).group("data"))
except Exception as excep:
json_data = {}
logging.error("WeiBoLogin get_json_data error: %s", excep)
return json_data
def get_password(self, servertime, nonce, pubkey):
"""
get legal password
"""
string = (str(servertime) + "\t" + str(nonce) + "\n" + str(self.pass_word)).encode("utf-8")
public_key = rsa.PublicKey(int(pubkey, 16), int("10001", 16))
password = rsa.encrypt(string, public_key)
password = binascii.b2a_hex(password)
return password.decode()
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='myweibo.log',
filemode='a')
weibo = WeiBoLogin()
weibo.login("[email protected]", "wenzhihuai2018.")