-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathspider.py
351 lines (272 loc) · 9.28 KB
/
spider.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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# -*- coding: utf8 -*-
import urllib2
from threading import Thread
import Queue
import re
import time
import sys
import urllib
import os
baseUrl = "http://www.chemicalbook.com/ProductCASList_12_%d00_EN.htm"
viewBaseUrl = "http://www.chemicalbook.com/ProductChemicalPropertiesCB%s_EN.htm"
viewUrlList = Queue.Queue(maxsize = 0)
listUrlList = Queue.Queue(maxsize = 0)
dataList = Queue.Queue(maxsize = 0)
pageDic = {};
idDic = {}
ISOTIMEFORMAT='%Y-%m-%d %X'
total = 0
totalGot = 0
getViewThreads = {}
listThreadNum = 30
viewThreadNum = 30
pIndex = 0
#proxies = ['110.4.12.170:80',]
proxies = [
#'111.1.55.19:8080',
'211.142.236.135:80',
'110.4.24.170:80',
#'203.86.79.227:80',
'221.10.40.232:81',
#'173.213.113.111:8089',
'219.239.227.81:8121',
'119.254.90.18:8080',
'121.26.229.197:8081',
'60.8.63.52:8081',
'125.91.4.146:3328',
'221.10.40.236:83',
'202.116.160.89:80',
'110.4.12.170:83',
'119.167.231.72:8080',
#'222.180.173.10:8080',
#'106.3.43.73:80',
''
] #'110.4.12.170:80','173.213.113.111:8089'
def logStatus(str):
fp = open("/spider.log","a")
fp.write(str+'\n');
fp.close()
def changeProxy():
global pIndex
proxy = proxies[pIndex]
pIndex += 1
if pIndex == len(proxies):
pIndex = 0
if proxy:
proxy_support = urllib2.ProxyHandler({'http':'http://'+proxy})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
else:
opener = urllib2.build_opener(urllib2.BaseHandler, urllib2.HTTPHandler)
urllib2.install_opener(opener)
def getUrlContent(url):
req = urllib2.Request(url)
req.add_header("Referer","http://www.chemicalbook.com/")
req.add_header("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36")
req.add_header("Cookie","ASP.NET_SessionId=j1vaqq55e5y5gu454ic3icrt")
fp = urllib2.urlopen(req)
content = fp.read()
fp.close()
return {'fp':fp,'content':content}
def forSafe():
global totalGot
global total
if total%500==0 and total>0:
logStatus('oh 500 ,change proxy')
changeProxy()
for k,thread in getViewThreads.items():
thread.waitLong = 600 #休息10分钟
try:
thread.fp.close()
except:
pass
if total%100==0 and total>0:
for k,thread in getViewThreads.items():
if 100>thread.wait:
thread.wait = 100
try:
thread.fp.close()
except:
pass
class getUrl(Thread):
def __init__(self,tid):
Thread.__init__(self)
self.tid = tid
self.wait = 0
self.waitLong = 0
def run(self):
global total
while True:
if self.wait>0:
print 'thread list_',self.tid,' waiting...'
time.sleep(self.wait)
self.wait = 0
if self.waitLong>0:
print 'thread list_',self.tid,' waitingLong...'
time.sleep(self.waitLong)
self.waitLong = 0
id = listUrlList.get()
url = baseUrl%(id,)
#print url
try:
content = getUrlContent(url)
self.fp = content['fp']
content = content['content']
except:
listUrlList.put(id)
continue
total += 1
#print 'the ',total,'st page'
if 'System busy' in content:
listUrlList.put(id)
global pIndex
logStatus('oh got some shit!'+str(pIndex))
time.sleep(60*60*2)
continue
viewList = re.findall("CB(\d+)\_EN\.htm",content);
pageList = re.findall("ProductCASList\_12\_(\d+)00\_EN\.htm",content);
for vid in viewList:
if idDic.has_key(vid):
continue
else:
idDic[vid] = 1
viewUrlList.put(vid);
for pid in pageList:
if pageDic.has_key(pid):
continue
else:
pageDic[pid] = 1
listUrlList.put(int(pid))
forSafe()
class getView(Thread):
def __init__(self,tid):
Thread.__init__(self)
self.tid = tid
self.wait = 0
self.waitLong = 0
def run(self):
global total
global totalGot
while True:
if self.wait>0:
print 'thread view_',self.tid,' waiting...'
time.sleep(self.wait)
self.wait = 0
if self.waitLong>0:
print 'thread view_',self.tid,' waitingLong...'
time.sleep(self.waitLong)
self.waitLong = 0
id = viewUrlList.get()
viewUrl = viewBaseUrl%(id,)
#print url
try:
content = getUrlContent(viewUrl)
self.fp = content['fp']
content = content['content']
except:
viewUrlList.put(id)
continue
total += 1
#print 'the ',total,'st page'
if 'System busy' in content:
global pIndex
logStatus('get view, oh got some shit!'+str(pIndex))
viewUrlList.put(id)
time.sleep(60*60*2)
continue
data = {'cas_index':1,'content':content,'id':id}
dataList.put(data)
totalGot += 1
#print "Geted:",id,time.strftime( ISOTIMEFORMAT, time.localtime() )
forSafe()
class SendData(Thread):
def __init__(self):
Thread.__init__(self)
self.hasSend = 0
print 'sendData'
def run(self):
while True:
data = dataList.get()
dataStr = urllib.urlencode(data)
try :
api = urllib.urlopen('http://www.mq35.com/gather_en/gather.php',dataStr)
insertId = api.read()
api.close()
self.hasSend += 1
except Exception,e:
print e
dataList.put(data)
time.sleep(2);
class Timer(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
t = 0
while True:
t+=1
ar = (t,totalGot,total,viewUrlList.qsize(),listUrlList.qsize(),ST.hasSend,dataList.qsize())
status = 'passed:%d,got:%d,page:%d,viewq:%d,pageq:%d,sended:%d,remain:%d'%ar;
# sys.stdout.write(status);
# sys.stdout.write('\r')
# sys.stdout.flush()
logFp = open('/spider.log',"a")
logFp.write(status+"\n")
logFp.close()
time.sleep(1)
def demaeon():
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
sys.exit(4)
os.chdir('/')
os.umask(0)
os.setsid()
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
sys.exit(4)
for f in sys.stdout, sys.stderr: f.flush()
si = file('/spider.log', 'r')
so = file('/spider.log', 'a+')
se = file('/spider.log', 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
demaeon()
print time.strftime( ISOTIMEFORMAT, time.localtime() )
#检查代理可用
for i in range(0,len(proxies)):
changeProxy()
cp = pIndex-1;
logStatus('check '+proxies[cp]+'...')
try:
c = getUrlContent('http://www.baidu.com');
if 'baidu' not in c['content']:
print proxies[cp],' seemed not available remove it';
proxies.remove(proxies[cp])
else:
logStatus( proxies[cp]+' available')
except Exception,e:
print e
cp = pIndex-1;
print proxies[cp],' seemed not available remove it';
proxies.remove(proxies[cp])
pIndex = 0
changeProxy()
for i in range(0,1):
listUrlList.put(i)
for i in range(0,listThreadNum):
getViewThreads['list_'+str(i)] = getUrl(i)
getViewThreads['list_'+str(i)].start()
#get view start...
for i in range(0,viewThreadNum):
getViewThreads['view_'+str(i)] = getView(i)
getViewThreads['view_'+str(i)].start()
print "Let's go timer:"
ST = SendData()
ST.start()
Timer().start()