weibo搜索爬虫

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
# coding: utf-8

__version__ = '1.1.0'
__author__ = 'Zhu Jianqi (heloowird@gmail.com)'

'''
以关键词收集新浪微博
'''
import requests
import wx
import csv
import codecs
import sys
import urllib
import urllib2
import re
import json
import hashlib
import os
import time
import datetime
import random
from lxml import etree
import logging
import gzip
from StringIO import StringIO

class CollectData():
"""数据收集类
利用微博高级搜索功能,按关键字搜集一定时间范围内的微博。

大体思路:构造URL,爬取网页,然后解析网页中的微博ID。后续利用微博API进行数据入库。本程序只负责收集微博的ID。

登陆新浪微博,进入高级搜索,输入关键字”空气污染“,选择”实时“,时间为”2013-07-02-2:2013-07-09-2“,地区为”北京“,之后发送请求会发现地址栏变为如下:
http://s.weibo.com/wb/%25E7%25A9%25BA%25E6%25B0%2594%25E6%25B1%25A1%25E6%259F%2593&xsort=time&region=custom:11:1000&timescope=custom:2013-07-02-2:2013-07-09-2&Refer=g

是不是很长,其实很简单。
固定地址部分:http://s.weibo.com/wb/
关键字二次UTF-8编码:%25E7%25A9%25BA%25E6%25B0%2594%25E6%25B1%25A1%25E6%259F%2593
排序为“实时”:xsort=time
搜索地区:region=custom:11:1000
搜索时间范围:timescope=custom:2013-07-02-2:2013-07-09-2
可忽略项:Refer=g
显示类似微博:nodup=1 注:这个选项可多收集微博,建议加上。默认不加此参数,省略了部分相似微博。
某次请求的页数:page=1

另外,高级搜索最多返回50页微博,那么时间间隔设置最小为宜。所以该类设置为搜集一定时间段内最多50页微博。
"""
def __init__(self, keyword, startTime, savedir, interval='50', flag=True, begin_url_per = "http://s.weibo.com/weibo/"):
self.begin_url_per = begin_url_per #设置固定地址部分,默认为"http://s.weibo.com/weibo/",或者"http://s.weibo.com/wb/"
self.setKeyword(keyword) #设置关键字
self.setStartTimescope(startTime) #设置搜索的开始时间
# self.setRegion(region) #设置搜索区域
self.setSave_dir(savedir) #设置结果的存储目录
self.setInterval(interval) #设置邻近网页请求之间的基础时间间隔(注意:过于频繁会被认为是机器人)
self.setFlag(flag) #设置
self.logger = logging.getLogger('main.CollectData') #初始化日志

##设置关键字
##关键字需解码
def setKeyword(self, keyword):
#self.keyword = keyword.decode('GBK').encode("utf-8")
self.keyword = keyword
print 'twice encode:',self.getKeyWord()

##设置起始范围,间隔为1小时
##格式为:yyyy-mm-dd-HH
def setStartTimescope(self, startTime):
if not (startTime == '-'):
self.timescope = startTime + ":" + startTime
else:
self.timescope = '-'

# ##设置搜索地区
# def setRegion(self, region):
# self.region = region

##设置结果的存储目录
def setSave_dir(self, save_dir):
self.save_dir = save_dir
if not os.path.exists(self.save_dir):
os.mkdir(self.save_dir)

##设置邻近网页请求之间的基础时间间隔
def setInterval(self, interval):
self.interval = int(interval)

##设置是否被认为机器人的标志。若为False,需要进入页面,手动输入验证码
def setFlag(self, flag):
self.flag = flag

##构建URL
def getURL(self):
return self.begin_url_per+self.getKeyWord()+"&typeall=1&suball=1"+"&timescope=custom:"+self.timescope+"&page="

##关键字需要进行两次urlencode
def getKeyWord(self):
once = urllib.urlencode({"kw":self.keyword})[3:]
return urllib.urlencode({"kw":once})[3:]

##爬取一次请求中的所有网页,最多返回50页
def download(self, url, maxTryNum=4):
csvFile = open(self.save_dir + os.sep + "weibo_kanbing.csv", "ab") #向结果文件中写微博ID
csvFile.write(codecs.BOM_UTF8)
content = csv.writer(csvFile, dialect='excel')
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
cookie = {'SINAGLOBAL':'3726160468139.8677.1489128973894', 'un':'18621677460', 'wvr':'6', 'SWB':'usrmdinst_12', 'SCF':'At4nsWXnBTiLQgwnhEdGW1ipfDRoyBYdEIpm4KN7_ZN3C0BxRlQeyX0sHoQOK6bDqLR6HeBBiwo6wRFXfObIvnc.', 'SUB':'_2A251wx_bDeRxGeNP7FIR9yjFwzyIHXVWuXYTrDV8PUNbmtBeLRjVkW8ia3o1WnWjknWq3t_Uh0UkKzBqsg..', 'SUBP':'0033WrSXqPxfM725Ws9jqgMF55529P9D9Wh_ODAX.pd3QJ6U3yvqGKET5JpX5KMhUgL.Fo-pS057S0q41h52dJLoIEUBBEXLxKqL1hnL1KnLxK-LBKeLB-zLxK-L1K5L1K2LxK-L12qLBoet', 'SUHB':'0vJ4Ss25HO1Ohu', 'ALF':'1521001227', 'SSOLoginState':'1489465228', '_s_tentry':'login.sina.com.cn', 'Apache':'7301168373695.357.1489465207066', 'ULV':'1489465207130:8:8:5:7301168373695.357.1489465207066:1489412710557', 'UOR':',,login.sina.com.cn', 'WBStorage':'02e13baf68409715|undefined'}

hasMore = True #某次请求可能少于50页,设置标记,判断是否还有下一页
isCaught = False #某次请求被认为是机器人,设置标记,判断是否被抓住。抓住后,需要复制log中的文件,进入页面,输入验证码
filter = set([]) #过滤重复的微博ID

i = 1 #记录本次请求所返回的页数
while hasMore and i < 51 and (not isCaught): #最多返回50页,对每页进行解析,并写入结果文件
source_url = url + str(i) #构建某页的URL
data = '' #存储该页的网页数据
goon = True #网络中断标记

##网络不好的情况,试着尝试请求三次
for tryNum in range(maxTryNum):
try:
# set header http://stackoverflow.com/questions/385262/how-do-i-send-a-custom-header-with-urllib2-in-a-http-request
# see this http://stackoverflow.com/questions/1653591/python-urllib2-response-header , so you can see 'gzip' in response header with urllib2.urlopen(URL).info()
# and this http://stackoverflow.com/questions/3947120/does-python-urllib2-automatically-uncompress-gzip-data-fetched-from-webpage teach you how to decode gzip
#
#r = requests.get(source_url, cookies=cookie, headers=headers, timeout=12)
send_headers = {
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding":"gzip, deflate, sdch",
"Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6",
"Cache-Control":"no-cache",
"Connection":"keep-alive",
#"Cookie":"cookies here"
"Host":"s.weibo.com",
"Pragma":"no-cache",
"Referer":"http://s.weibo.com/",
"Upgrade-Insecure-Requests":"1",
"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
}
req = urllib2.Request(source_url , headers=send_headers)
r = urllib2.urlopen(req)
if r.info().get('Content-Encoding') == 'gzip':
buf = StringIO(r.read())
f = gzip.GzipFile(fileobj=buf)
html = f.read()
else:
html = r.read()
data = html
#print data
break
except:
if tryNum < (maxTryNum-1):
time.sleep(10)
else:
print 'Internet Connect Error!'
self.logger.error('Internet Connect Error!')
self.logger.info('filePath: ' + self.save_dir)
self.logger.info('url: ' + source_url)
self.logger.info('fileNum: ' + str(fileNum))
self.logger.info('page: ' + str(i))
self.flag = False
goon = False
break
if goon:
lines = data.splitlines()
isCaught = True
for line in lines:
## 判断是否有微博内容,出现这一行,则说明没有被认为是机器人
if line.startswith('<script>STK && STK.pageletM && STK.pageletM.view({"pid":"pl_weibo_direct"'):
isCaught = False
n = line.find('html":"')
if n > 0:
j = line[n + 7: -12].encode("utf-8").decode('unicode_escape').encode("utf-8").replace("\\", "").decode('utf-8')
## 没有更多结果页面
if (j.find('<div class="search_noresult">') > 0):
hasMore = False
## 有结果的页面
else:
page = etree.HTML(j)
comment_box = page.xpath("//div[@action-type=\"feed_list_item\"]")
for each_comment in comment_box:
comment_time = each_comment.xpath(".//div[@class=\"feed_from W_textb\"]/a/@title")
comment_text_list = each_comment.xpath(".//p[@class='comment_txt']")
comment_text = []
for eachtext in comment_text_list:
comment_text = 'r'.join(eachtext.xpath(".//text()"))
comment_text = comment_text.replace(' ','').replace('\n', '').replace('\r', ' ')
comment_text = comment_text.encode('utf8')
if (comment_text != 'None' and comment_text not in filter):
filter.add(comment_text)
content.writerow([comment_time[0], comment_text])
# weibo = page.xpath("//div[@class=\"feed_from W_textb\"])
# for weibo_time, weibo_content in weibo:
# weibo_time = weibo_time.xpath("./[@class=\"feed_from W_textb\"]/a/@title")
# concept = 'r'.join(weibo_content.xpath("./text()"))
# concept = concept.replace(' ','').replace('\n','').replace('\r',' ')
# concept = concept.encode('utf8')
# if (concept != 'None' and concept not in filter):
# filter.add(concept)
# content.writerow([weibo_time, concept])

# dls_id = page.xpath("//div[@class=\"feed_from W_textb\"]/a/@title")
# for dl_id in dls_id:
# # mid = str(dl_id.attrib.get('nick-name'))
# dl_id = dl_id.encode('utf8')
# if (dl_id != 'None' and dl_id not in mid_filter):
# mid_filter.add(dl_id)
# content.writerow([dl_id])
#
# dls_text = page.xpath("//p[@class='comment_txt']")
# for dl_text in dls_text:
# concept = 'r'.join(dl_text.xpath("./text()"))
# concept = concept.replace(' ','').replace('\n','').replace('\r',' ')
# concept = concept.encode('utf8')
# if (concept != 'None' and concept not in mid_filter):
# mid_filter.add(concept)
# content.writerow([concept])
# content.writerow('\n')
# if (concept != 'None' and concept not in mid_filter):
# mid_filter.add(concept)
# content.write(concept)
# content.write('\n')
# print concept
# print "----------------------"
break
lines = None
## 处理被认为是机器人的情况
if isCaught:
print 'Be Caught!'
self.logger.error('Be Caught Error!')
self.logger.info('filePath: ' + self.save_dir)
self.logger.info('url: ' + source_url)
self.logger.info('fileNum: ' + str(fileNum))
self.logger.info('page:' + str(i))
data = None
self.flag = False
break
## 没有更多结果,结束该次请求,跳到下一个请求
if not hasMore:
print 'No More Results!'
if i == 1:
time.sleep(random.randint(55,75))
else:
time.sleep(15)
data = None
break
i += 1
## 设置两个邻近URL请求之间的随机休眠时间,防止Be Caught。目前没有模拟登陆
# sleeptime_one = random.randint(self.interval-30,self.interval-10)
# sleeptime_two = random.randint(self.interval+10,self.interval+30)
# if i%2 == 0:
# sleeptime = sleeptime_two
# else:
# sleeptime = sleeptime_one
# print 'sleeping ' + str(sleeptime) + ' seconds...'
# time.sleep(sleeptime)
else:
break
csvFile.close()
csvFile = None

##改变搜索的时间范围,有利于获取最多的数据
def getTimescope(self, perTimescope, hours):
if not (perTimescope=='-'):
times_list = perTimescope.split(':')
start_datetime = datetime.datetime.fromtimestamp(time.mktime(time.strptime(times_list[-1],"%Y-%m-%d-%H")))
start_new_datetime = start_datetime + datetime.timedelta(seconds = 3600)
end_new_datetime = start_new_datetime + datetime.timedelta(seconds = 3600*(hours-1))
start_str = start_new_datetime.strftime("%Y-%m-%d-%H")
end_str = end_new_datetime.strftime("%Y-%m-%d-%H")
return start_str + ":" + end_str
else:
return '-'

def main():
logger = logging.getLogger('main')
logFile = './collect.log'
logger.setLevel(logging.DEBUG)
filehandler = logging.FileHandler(logFile)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s')
filehandler.setFormatter(formatter)
logger.addHandler(filehandler)

while True:
## 接受键盘输入
keyword = raw_input('Enter the keyword(type \'quit\' to exit ):')
if keyword == 'quit':
sys.exit()
startTime = raw_input('Enter the start time(Format:YYYY-mm-dd-HH):')
# region = raw_input('Enter the region([BJ]11:1000,[SH]31:1000,[GZ]44:1,[CD]51:1):')
savedir = raw_input('Enter the save directory(Like C://data//):')
interval = raw_input('Enter the time interval( >30 and deafult:50):')

##实例化收集类,收集指定关键字和起始时间的微博
cd = CollectData(keyword, startTime, savedir, interval)
while cd.flag:
print cd.timescope
logger.info(cd.timescope)
url = cd.getURL()
cd.download(url)
cd.timescope = cd.getTimescope(cd.timescope,1) #改变搜索的时间,到下一个小时
else:
cd = None
print '-----------------------------------------------------'
print '-----------------------------------------------------'
else:
logger.removeHandler(filehandler)
logger = None
if __name__ == '__main__':
main()