-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitterscraping.py
270 lines (237 loc) · 7.86 KB
/
twitterscraping.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
# -*- coding: utf-8 -*-
import urllib2,urllib
import simplejson
class Twitter:
def __init__(self, userdata):
self.user = userdata
self.url = "twitter.com"
self.serviceName = "Twitter API"
self.serviceURL = "twitter.com"
def setUser(self,userdata):
self.user = userdata
def setAuthService(self,service):
if service == "twitter":
self.serviceName = "Twitter API"
self.serviceURL = "twitter.com"
self.url = "twitter.com"
if service == "wassr":
self.serviceName = "API Authentication"
self.serviceURL = "api.wassr.jp:80"
self.url = "api.wassr.jp"
def setAuthHandler(self):
#ユーザ名等設定する
#初回時のみで充分かなぁ
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(self.serviceName,self.serviceURL,self.user['user'],self.user['pass'])
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
return opener
def getHttpJson(self,url):
self.setAuthHandler()
data = urllib2.urlopen(url)
urlstring = data.read()
a = simplejson.loads(urlstring)
return a
def get(self,username):
a = self.getHttpJson("http://%s/statuses/friends_timeline.json" % self.url)
return self.parseTwitJSON(a)
def getPublicTimeline(self):
a = self.getHttpJson("http://%s/statuses/public_timeline.json" % self.url)
return self.parseTwitJSON(a)
def getReplies(self,username):
a = self.getHttpJson("http://%s/statuses/replies.json" % self.url)
return self.parseTwitJSON(a)
def getDM(self,username):
s = "http://%s/direct_messages.json" % self.url
#print "url+" +s
a = self.getHttpJson(s)
return self.parseTwitJSONDM(a)
def getWithPage(self,username,num):
# page番号つきget
self.setAuthHandler()
s = "http://%s/statuses/friends_timeline.json?page=%d" % self.url, num
print "url+" +s
a = self.getHttpJson(s)
return self.parseTwitJSON(a)
def getWithUser(self,user):
# page番号つきget
self.setAuthHandler()
s = "http://%s/statuses/user_timeline/%s.json" % (self.url, user)
print "url+" +s
a = self.getHttpJson(s)
return self.parseTwitJSON(a)
def getWithUserPage(self,username,num):
# page番号つきget
self.setAuthHandler()
s = "http://%s/statuses/user_timeline/%s.json?page=%d" % (self.url, username, num)
print "url+" +s
a = self.getHttpJson(s)
return self.parseTwitJSON(a)
def getFollowersLite(self,username):
# followerを取得
self.setAuthHandler()
# ここ変える
s = "http://%s/statuses/followers.json?lite=true" % self.url
print "url+" +s
a = self.getHttpJson(s)
return self.parseTwitJSONFollowers(a)
def parseTwitJSON(self,a):
result = []
for x in a:
resultSub = []
#resultSub.append(x['created_at'])
#print x
y = x['user']
resultSub.append(y['screen_name'])
resultSub.append(x['text'])
if self.url != "api.wassr.jp" :
resultSub.append(x['created_at'])
else:
resultSub.append(0)
resultSub.append(y['profile_image_url'])
resultSub.append(y['id'])
result.append(resultSub)
#print resultSub[0]+resultSub[1]
return result
def parseTwitJSONDM(self,a):
result = []
for x in a:
resultSub = []
#resultSub.append(x['created_at'])
y = x['sender']
resultSub.append(y['screen_name'])
resultSub.append(x['text'])
resultSub.append(x['created_at'])
resultSub.append(y['profile_image_url'])
resultSub.append(y['id'])
result.append(resultSub)
#print resultSub[0]+resultSub[1]
return result
def parseTwitJSONFollowers(self,a):
result = []
for x in a:
resultSub = []
#resultSub.append(x['created_at'])
#y = x['sender']
resultSub.append(x['screen_name'])
#resultSub.append(x['text'])
#resultSub.append(x['created_at'])
result.append(resultSub)
#print resultSub[0]+resultSub[1]
return result
def put(self,s):
self.setAuthHandler()
postdata = {}
postdata['status'] = s.encode('utf-8')
#if self.url == "api.wassr.jp" :
postdata['source']='crochet'
param = urllib.urlencode(postdata)
data = urllib2.urlopen("http://%s/statuses/update.json" % self.url, param)
print data.read()
"""
Favする
"""
def createFavorite(self,id):
self.setAuthHandler()
postdata = {}
#if self.url == "api.wassr.jp" :
# postdata['source']='crochet'
#postdata['source'] = s
param = urllib.urlencode(postdata)
url = "http://%s/favorites/create/%d.json" % self.url, id
data = urllib2.urlopen(url,param)
print data.read()
"""
サインインします
In: なし(クラスメンバ変数でuser,pass)
"""
def singIn(self,s):
import cookielib
postdata = {}
postdata['authenticity_token'] = "b849505a78a9c15242069df3b3f1cc823cc22084"
postdata['session[username_or_email]'] = self.user['user']
postdata['session[password]'] = self.user['pass']
postdata['remember_me'] = "1"
#postdata['source'] = s
en_post_data = urllib.urlencode(postdata)
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# ログイン/cookie取得
r = opener.open("http://twitter.com/sessions",en_post_data)
r.read()
return opener
def getWithScraping(self,user,num=1):
#ログイン必要?
opener = self.singIn("")
s = "http://%s/home?page=%d" % self.url, num
data = opener.open(s)
urlstring = data.read()
#print urlstring
if num == 1:
return self.scrapeTwit(urlstring,True)
else:
return self.scrapeTwit(urlstring,False)
def getUserPageWithScraping(self,user,num):
self.setAuthHandler()
s = "http://%s/%s?page=%d" % self.url, user, num
print "url+" +s
data = urllib2.urlopen(s)
urlstring = data.read()
if num == 1:
return self.scrapeTwitUserPage(urlstring,True)
else:
return self.scrapeTwitUserPage(urlstring,False)
# HTMLをスクレイプします。
def scrapeTwitUserPage(self,a,isFirst):
import re
# <span class="entry-title entry-content">~</span>(最短)
#reg = re.compile(r'<(.*?)>')
retList = []
reg = re.compile("<span class=\"entry-title entry-content\">([\w\W]*?)</span>[\w\W]*?<abbr class=\"published\" title=\"([\w\W]*?)\">.*?</abbr>",re.MULTILINE)
reg2 = re.compile("<span class=\"entry-content\">([\w\W]*?)</span>[\w\W]*?<span class=\"published\" title=\"([\w\W]*?)\">.*?</span>",re.MULTILINE)
# もし1ページ目なら、最新の発言も取ってくる
#if isFirst :
# a3 = reg.findall(a)
# retList.append( a3[0] )
a2 = reg2.findall(a)
for aa in a2:
retList.append( (aa[0].strip(),aa[1]) )
return retList
def scrapeTwit(self,str,flag):
import re
regTwit = re.compile("<tr [\w\W]*?(id=[\w\W]*?)</tr>",re.MULTILINE)
regStatusID = re.compile("id=\"status_(\d*?)\"")
regImage = re.compile("<img [\w\W]*? src=\"([\w\W]*?)\"",re.MULTILINE)
regUserAndMessage = re.compile("<td class=\"status-body\">([\w\W]*?)</td>")
regUser = re.compile("<a href=.*?>(.*?)</a>")
regMessage= re.compile("<span class=\"entry-content\">\s*?(\S[\w\W]*?)</span>",re.MULTILINE)
regTime = re.compile("<span class=\"[\w\W]*?\" title=\"([\w\W]*?)\">")
regATagBegin = re.compile("<a href=.*?>")
str = str.replace("\t","")
str = str.replace("\n","")
a = regTwit.findall(str)
resultList = []
for aa in a:
resultData = {}
statusID = regStatusID.search(aa)
resultData['statusID'] = statusID.group(1)
b = regImage.search(aa)
resultData['image'] = b.group(1)
c = regUserAndMessage.search(aa).group(1)
d1 = regUser.search(c)
d2 = regMessage.search(c)
resultData['user'] = unicode(d1.group(1),'utf-8')
message = unicode(d2.group(1),'utf-8')
#message2 = regATagBegin.sub("",message)
#resultData['message'] = message2.replace("</a>","")
resultData['message'] = message
tm = regTime.search(aa)
resultData['time'] = tm.group(1)
result = []
result.append(resultData['user'])
result.append(resultData['message'].replace("<","<").replace(">",">"))
result.append(resultData['time'])
result.append(resultData['image'])
result.append(resultData['statusID'])
resultList.append(result)
return resultList