/
crawler_v11.py
1804 lines (1518 loc) · 73.6 KB
/
crawler_v11.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding: utf-8
# In[1]:
from urllib.parse import urlencode
import requests
from bs4 import BeautifulSoup
from lxml import etree
import time
import re
from fake_useragent import UserAgent
import sys
# In[2]:
class CmpyinfoCrawlerError(Exception):
def __init__(self, prefix, sta=0):
self.sta = sta
self.end = time.time()
self.exe = self.end - self.sta
self.prefix = prefix
def __str__(self):
def timestr(t):
d, r = divmod(t, 86400)
h, r = divmod(r, 3600)
m, s = divmod(r, 60)
return "{} days {:02}:{:02}:{:.2f}".format(d, h, m, s)
s = self.prefix + " raised at {} ".format(timestr(self.end-self.sta))
return s
# In[3]:
import proxypool
#p = proxypool()
#p.na_proxy()
#print(p.proxy_set)
#p.filter_proxy()
# In[4]:
class back_log:
def __init__(self, flush=False, flush_threshold=1000, first_line='',log_format='', fname =''):
self.queue = list()
self.flush = flush
self.flush_threshold = flush_threshold
self.first_line = first_line
self.log_format = log_format
self.fname = fname
with open(fname, 'a') as log_file:
if self.first_line:
log_file.write(self.first_line + '\n')
def log(self, mode='format', args = tuple(), in_log='', postfix=''):
if mode == 'format':
log_str = self.log_format.format(*args) + ' ' + postfix
elif mode == 'manual':
log_str = in_log + ' ' + postfix
self.queue.append(log_str)
if len(self.queue) >= self.flush_threshold:
log_str = '\n'.join(self.queue)
self.log_flush()
def log_flush(self):
if self.queue:
log_str = '\n'.join(self.queue)
with open(self.fname, 'a') as log_file:
log_file.write(log_str + '\n')
self.flush = False
del self.queue
self.queue = list()
# In[5]:
from collections import defaultdict
from datetime import datetime
import copy
import pandas as pd
import json
import pickle
#d = defaultdict(set)
class cmpyinfo_crawler:
#proxies = [{'http':'http://proxy.hinet.net:80'}, {'http':'172.103.3.156:53281'}]
h3_dict = {
'公司基本資料':'Cmpy',
'大陸公司許可報備基本資料':'CmpyCnRp', # 53656300
'大陸公司許可基本資料':'CmpyCn',# 53026057
'外國公司報備基本資料':'CmpyFrgnRp', # 16747659
'外國公司認許基本資料':'CmpyFrgn', # 24812289
'商業登記基本資料':'Busm',
'商業登記基本資料(分支機構)':'BrBusm', # 02284257
'工廠基本資料':'Fact',
'分公司資料':'BrCmpy',
'有限合夥登記基本資料':'Lmtd',
'有限合夥登記基本資料(分支機構)':'BrLmtd'
}
url2_dict = {
'HC' : 'http://findbiz.nat.gov.tw/fts/query/QueryCmpyDetail/queryCmpyDetail.do',
'HB' : 'http://findbiz.nat.gov.tw/fts/query/QueryBusmDetail/queryBusmDetail.do',
'BB' : 'http://findbiz.nat.gov.tw/fts/query/QueryBusmDetail/queryBusmDetail.do',
'HF' : 'http://findbiz.nat.gov.tw/fts/query/QueryFactDetail/queryFactDetail.do',
'BC' : 'http://findbiz.nat.gov.tw/fts/query/QueryBrCmpyDetail/queryBrCmpyDetail.do',
'HL' : 'http://findbiz.nat.gov.tw/fts/query/QueryLmtdDetail/queryLmtdDetail.do',
'BL' : 'http://findbiz.nat.gov.tw/fts/query/QueryLmtdDetail/queryLmtdDetail.do'
}
cmpy_type_dict = {
'HC' : 'Cmpy',
'HB' : 'Busm',
'BB' : 'Busm',
'HF' : 'Fact',
'BC' : 'BrCmpy',
'HL' : 'Lmtd',
'BL' : 'BrLmtd'
}
ua = UserAgent()
#proxy = proxypool()
def __init__(self, qryCond='', qryType='', pageStart=1, pageEnd=1, path_phantomjs = '/usr/local/Cellar/phantomjs/2.1.1/bin/phantomjs', logname = 'task.log', sleep_scale='small'):
self.path_phantomjs = path_phantomjs
self.session = None
self.pageStart = pageStart
self.pageNow = pageStart
self.pageEnd = pageEnd
self.pageItem = 1
self.qryCond = qryCond
self.qryType = qryType
# self.banKey = None
# self.objectId = None
"""
self.task = {'qryCond': self.qryCond,
'qryType': self.qryType,
'pageStart': self.pageStart,
'pageEnd': self.pageEnd,
'pageNow': self.pageNow,
'pageItem' : self.pageItem}
"""
self.banNo = None
self.brBanNo = None
self.banKey = None
self.estbId = None
self.objectId = None
self.objectId64 = None
self.querytype = None
#self.cmpy_type = None
self.cookie = None
self.oncontextmenu = list()
# to gater h3_text of each
self.h3_info = defaultdict(set)
self.response = None
self.h3_text = None
self.h3_query = None
self.user_agent = None
#self.proxyip()
self.sta = time.time()
self.end = time.time()
self.this_round_sta = time.time()
self.this_round_end = time.time()
self.pooling = time.time()
#self.tick = 300
#self.proxy_pool = [{'http':'proxy.hinet.net:80'}, None]
self.proxypool = proxypool.proxypool(path_phantomjs=path_phantomjs)
self.proxy_ratio = 5 # 5 proxies vs 1 None
self.proxy_i = 0
self.proxy = None
#self.proxy_pool = [None, None]
#self.proxy_set = bool(proxy)
self.proxy_update = True
self.proxy_tick = 1800
#self.proxy_tick = 120
#self.proxy_tick = 300
#self.new_proxies()
#self.proxyip(mode = 1, top = 0)
self.totalPage = 1
self.totalCount = 1
self.flush_threshold = 20
self.total_json_name = "all_json_out"
self.search_error_cnt = 0
# self.trlog = back_log(flush=False, flush_threshold=1, first_line='',logformat='', fname ='')
# self.objidlog = back_log(flush=False, flush_threshold=1, first_line='',logformat='', fname ='')
def tasklog_timestamp():
d = datetime.now()#.strftime("%Y-%m-%d-%m-%s")
d.year,d.month,d.day,d.hour,d.minute,d.second
nowstr = "{0:0>4d}{1:0>2d}{2:0>2d}_{3:0>2d}{4:0>2d}{5:0>2d}".format(d.year,d.month,d.day,d.hour,d.minute,d.second)
return nowstr
self.timestamp = tasklog_timestamp()
self.tasklog = back_log(flush=False,
flush_threshold=100,
first_line='{0: >19s}, {1: >19s}, {2: >6s}, {3: >6s}'.format('task execution time', 'this round time', 'page', 'item'),
log_format= '{0: >19s}, {1: >19s}, {2: >6d}, {3: >6d}',
fname = '{}@{: >17s}.task.log'.format(logname, str(self.timestamp)))
self.parser = {'Cmpy':parser_cmpy_type('Cmpy', self.tasklog),
'CmpyFrgnRp':parser_cmpy_type('CmpyFrgnRp', self.tasklog),
'CmpyFrgn':parser_cmpy_type('CmpyFrgn', self.tasklog),
'CmpyCnRp':parser_cmpy_type('CmpyCnRp', self.tasklog),
'CmpyCn':parser_cmpy_type('CmpyCn', self.tasklog),
'BrCmpy':parser_cmpy_type('BrCmpy', self.tasklog),
'Busm':parser_cmpy_type('Busm', self.tasklog),
'BrBusm':parser_cmpy_type('BrBusm', self.tasklog),
'Fact':parser_cmpy_type('Fact', self.tasklog),
'Lmtd':parser_cmpy_type('Lmtd', self.tasklog),
'BrLmtd':parser_cmpy_type('BrLmtd', self.tasklog)}
self.tr = dict()
self.trlog = dict()
self.objidlog = dict()
self.results = defaultdict(list)
#self.flush_threshold = 20;
self.exception_happened = False
self.sleep_scale = sleep_scale
def __str__(self):
#attr = {"session":self.session, "qryCond":self.qryCond, "banNo":self.banNo, "brBanNo":self.brBanNo, "banKey":self.banKey, "estbId":self.estbId, "objectId":self.objectId, "querytype":self.querytype, "cmpy_type":self.cmpy_type, "h3_text":self.h3_text}
attr = {"session":self.session, "qryCond":self.qryCond, "banNo":self.banNo, "brBanNo":self.brBanNo, "banKey":self.banKey, "estbId":self.estbId, "objectId":self.objectId, "querytype":self.querytype, "h3_text":self.h3_text, "h3_query":self.h3_query}
return str(attr) + " " + self.exectime('task execution time: ')
def timestr(self, t):
d, r = divmod(t, 86400)
h, r = divmod(r, 3600)
m, s = divmod(r, 60)
return "{: >4d} days {: >2d}:{: >2d}:{: >2d}".format(int(d), int(h), int(m), int(s))
def exectime(self, prefix = ''):
# task execution time
self.end = time.time()
return prefix + self.timestr(self.end - self.sta)
def this_round_time_start(self):
self.this_round_sta = time.time()
#def this_round_time_end(self):
# self.this_round_end = time.time()
def this_round_exectime(self, prefix = ''):
# page execution time
self.this_round_end = time.time()
return prefix + self.timestr(self.this_round_end - self.this_round_sta)
def get_banKey_objectId(self, attri):
def objectId_base64(objectId):
import base64
b_objectId = str.encode(objectId) # str to byte str
encoded_b_objectId = base64.b64encode(b_objectId)
return encoded_b_objectId.decode('utf8')
# 必須透過objectId來決定要如何填入header
self.objectId = (attri.replace("javascript:qryDetail('","")).replace("', true);return false;","")
self.objectId64 = objectId_base64(self.objectId)
self.querytype = self.objectId[0:2]
#self.cmpy_type = cmpyinfo_crawler.cmpy_type_dict[self.querytype]
try:
if self.querytype not in cmpyinfo_crawler.url2_dict:
raise CmpyinfoCrawlerError('QueryTypeError', self.sta)
except CmpyinfoCrawlerError as ccerr:
print(ccerr)
return
# 按照objectId[0:2]來決定如何填入header
if self.querytype == 'HC': # 公司
self.banNo = self.objectId.replace('HC', '')
self.brBanNo = ''
self.banKey = ''
self.estbId = ''
elif self.querytype == 'BC': # 分公司
self.banNo = ''
self.brBanNo = self.objectId.replace('BC', '')
self.banKey = ''
self.estbId = ''
elif self.querytype == 'HB': # 商號
#self.banNo = self.qryCond
self.banNo = self.objectId[2:2+8]
self.brBanNo = ''
#self.banKey = self.objectId[self.objectId.rindex(self.qryCond) + len(self.qryCond):]
self.banKey = self.objectId[2+8:]
self.estbId = ''
elif self.querytype == 'BB': # 商號分公司
#self.banNo = self.qryCond
self.banNo = self.objectId[2:2+8]
self.brBanNo = ''
#self.banKey = self.objectId[self.objectId.rindex(self.qryCond) + len(self.qryCond):]
self.banKey = self.objectId[2+8:]
self.estbId = ''
elif self.querytype == 'HF': # 工廠
self.banNo = ''
self.brBanNo = ''
self.banKey = ''
self.estbId = self.objectId.replace('HF', '')
elif self.querytype == 'HL': # 有限合夥
self.banNo = self.objectId.replace('HL', '')
self.brBanNo = ''
self.banKey = ''
self.estbId = ''
elif self.querytype == 'BL': # 有限合夥分支
self.banNo = self.objectId.replace('BL', '')
self.brBanNo = ''
self.banKey = ''
self.estbId = ''
#print('banNo:', self.banNo, 'brBanNo:', self.brBanNo, 'banKey:', self.banKey, 'estbId:', self.estbId, 'querytype:', self.querytype)
def first_connection_header0(self):
self.form_data_url1 = dict()
self.form_data_url1 = {'qryCond':str(self.qryCond),
'infoType':'D',
'qryType':'',
'cmpyType':'',
'brCmpyType':'',
'busmType':'',
'factType':'',
'lmtdType':'',
'isAlive':'all',
'sugCont':'',
'sugEmail':'',
'g-recaptcha-response':''
}
#if len(self.qryType) > 1:
# self.form_data_url1['isAlive'] = 'all'
#else:
# self.form_data_url1['isAlive'] = 'true'
for qry in self.qryType:
if qry == 'cmpyType':
self.form_data_url1['qryType'] = 'cmpyType'
self.form_data_url1['cmpyType'] = 'true'
if qry == 'brCmpyType':
self.form_data_url1['qryType'] = 'brCmpyType'
self.form_data_url1['brCmpyType'] = 'true'
if qry == 'busmType':
self.form_data_url1['qryType'] = 'busmType'
self.form_data_url1['busmType'] = 'true'
if qry == 'factType':
self.form_data_url1['qryType'] = 'factType'
self.form_data_url1['factType'] = 'true'
if qry == 'lmtdType':
self.form_data_url1['qryType'] = 'lmtdType'
self.form_data_url1['lmtdType'] = 'true'
def first_connection_header1(self, currentPage):
self.form_data_url1 = dict()
self.form_data_url1 = {'pagingModel.totalCount':str(self.totalCount),
'pagingModel.currentPage':str(currentPage),
'pagingModel.totalPage':str(self.totalPage),
'model.qryCond':str(self.qryCond),
'model.isAlive':'all',
'model.cmpyType':'',
'model.brCmpyType':'',
'model.busmType':'',
'model.factType':'',
'model.lmtdType':'',
'model.infoType':'D',
'model.busiItemSub':'',
'model.city':''}
for qry in self.qryType:
if qry == 'cmpyType':
self.form_data_url1['model.cmpyType'] = 'true'
if qry == 'brCmpyType':
self.form_data_url1['model.brCmpyType'] = 'true'
if qry == 'busmType':
self.form_data_url1['model.busmType'] = 'true'
if qry == 'factType':
self.form_data_url1['model.factType'] = 'true'
if qry == 'lmtdType':
self.form_data_url1['model.lmtdType'] = 'true'
def set_form_data_url1(self, mode, currentPage=1):
if mode == 0:
self.first_connection_header0()
elif mode == 1:
self.first_connection_header1(currentPage)
def new_session(self):
if self.proxy_update:
if self.session is not None:
self.session.close()
self.session = requests.Session()
self.proxy_update = False
def first_connection(self):
url1 = 'http://findbiz.nat.gov.tw/fts/query/QueryList/queryList.do'
request_header1 = {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
##'Content-Length':'239',
'Content-Type':'application/x-www-form-urlencoded',
##'Cookie':'qryCond=00114003~type=cmpyType,brCmpyType,busmType,factType,lmtdType,~infoType=D~isAlive=all~; JSESSIONID=6D2FA44A8850268F8A6A9D429D53B548; DWRSESSIONID=*o94X5xiFwhD8b5kRGWQo7XpKTl; JSESSIONID=33352345177332F62F210E99D78BD44A; _ga=GA1.3.315276753.1502943360; _gid=GA1.3.754870603.1502943360; _gat=1',
'Host':'findbiz.nat.gov.tw',
'Origin':'http://findbiz.nat.gov.tw',
'Referer':'http://findbiz.nat.gov.tw/fts/query/QueryBar/queryInit.do',
'Upgrade-Insecure-Requests':'1',
#'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36'
}
#if get_new_session:
if self.proxy_update:
# 新的session 會換瀏覽器,並且拿新的session
request_header1['User-Agent'] = cmpyinfo_crawler.ua.random
# self.new_session()會將proxy_update設為False,所以要放後面
self.new_session()
try:
self.response = self.session.post(url1, headers=request_header1, data=self.form_data_url1, proxies=self.proxy)
except requests.exceptions.ProxyError as err:
self.tasklog.log(mode='manual', in_log = "Exception requests.ProxyError @ first_connection(), remove proxy")
self.change_proxy()
#self.response = self.session.post(url1, headers=request_header1, data=self.form_data_url1, proxies=self.proxy)
return False
except Exception as err:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception @ first_connection()")
print(err.__doc__)
self.tasklog.log(mode='manual', in_log = err.__doc__)
self.tasklog.log_flush()
self.change_proxy()
return False
try:
if self.response.status_code != 200:
raise CmpyinfoCrawlerError('Response200Error', self.sta)
except CmpyinfoCrawlerError as ccerr:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception @ first_connection()")
print(ccerr)
self.tasklog.log(mode='manual', in_log = str(ccerr))
self.tasklog.log_flush()
self.change_proxy()
return False
except Exception as err:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception @ first_connection()")
print(err.__doc__)
self.tasklog.log(mode='manual', in_log = err.__doc__)
self.tasklog.log_flush()
self.change_proxy()
return False
try:
selector = etree.HTML(self.response.content)
except Exception as err:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception from etree @ first_connection()")
print(err.__doc__)
self.tasklog.log(mode='manual', in_log = err.__doc__)
self.tasklog.log_flush()
self.change_proxy()
return False
# reCaptcha 測試
try:
recaptcha = selector.xpath('//div[@class="g-recaptcha"]')
if recaptcha:
raise CmpyinfoCrawlerError('reCaptchaError', self.sta)
except CmpyinfoCrawlerError as ccerr:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception @ first_connection()")
print(ccerr)
self.tasklog.log(mode='manual', in_log = str(ccerr))
self.tasklog.log_flush()
self.change_proxy()
return False
except Exception as err:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception from recaptcha@ first_connection()")
print(err.__doc__)
self.tasklog.log(mode='manual', in_log = err.__doc__)
self.tasklog.log_flush()
self.change_proxy()
return False
# 同一統編可有多個結果
#hrefs = selector.xpath('//*[@id="vParagraph"]/div[@class="panel panel-default"]/div[@class="panel-heading companyName"]/a')
hrefs = selector.xpath('//*[@id="vParagraph"]/div[@class="panel panel-default"]/div[2]/span')
del self.oncontextmenu
self.oncontextmenu = list()
for h in hrefs:
#if h.attrib['oncontextmenu'] not in self.oncontextmenu:
if 'oncontextmenu' in h.attrib and h.attrib['oncontextmenu'] not in self.oncontextmenu:
self.oncontextmenu.append(h.attrib['oncontextmenu'])
try:
if not self.oncontextmenu:
raise CmpyinfoCrawlerError('searchFailError', self.sta)
else:
return True
except CmpyinfoCrawlerError as ccerr:
self.search_error_cnt = self.search_error_cnt + 1
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception @ first_connection()")
print(ccerr)
self.tasklog.log(mode='manual', in_log = str(ccerr))
self.tasklog.log_flush()
self.change_proxy()
return False
except Exception as err:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception from oncontextmenu@ first_connection()")
print(err.__doc__)
self.tasklog.log(mode='manual', in_log = err.__doc__)
self.tasklog.log_flush()
self.change_proxy()
return False
def second_connection(self):
url2 = cmpyinfo_crawler.url2_dict[self.querytype]
form_data_url2 = {
'banNo':str(self.banNo),
'brBanNo':str(self.brBanNo),
'banKey':str(self.banKey),
'estbId':str(self.estbId),
'objectId':str(self.objectId64),
'CPage':'',
'brCmpyPage':'',
'eng':'',
}
request_header2={
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
##'Content-Length':'211',
##'Content-Type':'application/x-www-form-urlencoded',
##'Cookie':'JSESSIONID=3193CF8D61AEC43F3810BF07524701BA; DWRSESSIONID=*o94X5xiFwhD8b5kRGWQo7XpKTl; _gat=1; _ga=GA1.3.315276753.1502943360; _gid=GA1.3.754870603.1502943360',
'Host':'findbiz.nat.gov.tw',
'Origin':'http://findbiz.nat.gov.tw',
'Referer':'http://findbiz.nat.gov.tw/fts/query/QueryList/queryList.do',
##'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36'
}
ua = UserAgent()
request_header2['User-Agent'] = cmpyinfo_crawler.ua.random
#self.response = self.session.post(url2, headers=request_header2,data=form_data_url2, proxies=self.proxy) # first connection有機會重新設定self.proxy, second connection直接用
try:
self.response = self.session.post(url2, headers=request_header2,data=form_data_url2, proxies=self.proxy) # first connection有機會重新設定self.proxy, second connection直接用
except requests.exceptions.ProxyError as err:
self.tasklog.log(mode='manual', in_log = "Exception requests.ProxyError @ second_connection(), remove proxy")
self.change_proxy()
return False
except Exception as err:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception @ second_connection()")
print(err.__doc__)
self.tasklog.log(mode='manual', in_log = err.__doc__)
self.tasklog.log_flush()
self.change_proxy()
return False
try:
if self.response.status_code != 200:
raise CmpyinfoCrawlerError('Response200Error', self.sta)
except CmpyinfoCrawlerError as ccerr:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception @ second_connection()")
print(ccerr)
self.tasklog.log(mode='manual', in_log = str(ccerr))
self.tasklog.log_flush()
self.change_proxy()
return False
return True
# 由h3解析出來的中文字串才是比較精確的類型
def get_h3(self):
selector = etree.HTML(self.response.content)
h3 = selector.xpath('//div[@id="content"]/div[@class="tab-content"]/div[@class="tab-pane active"]/h3')
try:
if len(h3) == 0:
raise CmpyinfoCrawlerError('h3ResolveError', self.sta)
except CmpyinfoCrawlerError as ccerr:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception @ get_h3(): can't resolve h3 in xpath")
print(ccerr)
self.tasklog.log(mode='manual', in_log = str(ccerr))
self.tasklog.log_flush()
return False
self.h3_text = h3[0].text.encode('latin_1', errors='ignore').decode('utf8', errors='ignore')
self.h3_text = re.sub(r'\s', r'', self.h3_text)
print('self.h3_text resolved: ', self.h3_text)
#print(self.h3_text)
if self.h3_text in cmpyinfo_crawler.h3_dict:
self.h3_query = cmpyinfo_crawler.h3_dict[self.h3_text]
print('self.h3_query resolved: ', self.h3_query)
try:
if self.h3_text not in cmpyinfo_crawler.h3_dict:
raise CmpyinfoCrawlerError('h3ResolveError', self.sta)
except CmpyinfoCrawlerError as ccerr:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Exception @ get_h3(): new h3 found")
print(ccerr)
self.tasklog.log(mode='manual', in_log = str(ccerr))
self.tasklog.log_flush()
return False
return True
def proxy_monitor(self):
if self.proxy_tick < 0:
return
self.end = time.time()
if self.end - self.pooling > self.proxy_tick:
self.change_proxy()
self.pooling = time.time()
def renew_poroxypool(self):
self.proxypool.reset_proxy()
# 更新proxypool,先拿亞洲,拿不到就拿全世界
try:
self.proxypool.group_proxy()
if len(self.proxypool.proxy_set) == 0:
raise CmpyinfoCrawlerError('ResolveProxyError', self.sta)
except CmpyinfoCrawlerError as cerr:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Can not resolve proxy from proxypool.group _proxy(), retry proxypool.group_proxy()")
print(ccerr)
self.tasklog.log(mode='manual', in_log = str(ccerr))
self.tasklog.log_flush()
try:
self.proxypool.group_proxy()
if len(self.proxypool.proxy_set) == 0:
raise CmpyinfoCrawlerError('ResolveProxyError', self.sta)
except:
self.exception_happened = True
self.tasklog.log(mode='manual', in_log = "Can not resolve proxy from proxypool.group_proxy(), you can only use local ip")
print(ccerr)
self.tasklog.log(mode='manual', in_log = str(ccerr))
self.tasklog.log_flush()
return False
#self.proxypool.filter_proxy()
proxy_str = 'resolved ' + str(len(self.proxypool.proxy_set)) + ' proxies'
print(proxy_str)
self.tasklog.log(mode='manual', in_log = proxy_str)
return True
def set_proxy(self, p):
self.proxy = p
proxy_str = 'proxy change to ' + str(self.proxy) + ' @ ' + self.exectime('task execution time: ')
print(proxy_str)
self.tasklog.log(mode='manual', in_log = proxy_str)
self.proxy_update = True
def change_proxy(self):
#ratio = 5 # 5 proxies vs 1 None
#import random
#self.proxy_list = self.proxypool.proxy_list self.proxy_list[0]
if not self.proxypool.proxy_set:
self.renew_poroxypool()
#self.proxy_i += 1
#if self.proxy_i % self.proxy_ratio == 0:
# p = None
#else:
# p = {'http':self.proxypool.random_choice_one_proxy()}
p = self.proxypool.random_choice_one_proxy_with_none_freq()
self.set_proxy(p)
#self.proxy_update = True
def random_sleep(self, scale = 'small'):
import random
# 15% 20% 20% 10% 15% 20%
sleeptime = [1,1,1,2,2,2,2,3,3,3,3,4,4,5,5,5,6,6,6,6]
# 15% 35% 15% 15% 5% 15%
magnitude = [0.75, 0.75, 0.75, 1, 1, 1, 1, 1, 1, 1, 1.25, 1.25, 1.25, 1.5, 1.5, 1.5, 1.75, 2, 2, 2]
# 10%20% 30% 40%
basetime = [5, 7.5, 7.5, 10, 12.5, 12.5, 3, 3, 3, 3]
if scale == 'none':
return
if scale == 'mixed':
scale = random.choice(['small']+['midium']+['large'])
if scale == 'mixed_small':
scale = random.choice(['small']*14+['midium']*3+['large']*3)
if scale == 'mixed_medium':
scale = random.choice(['small']*3+['midium']*14+['large']*3)
if scale == 'mixed_large':
scale = random.choice(['small']*3+['midium']*3+['large']*14)
m = random.choice(magnitude)
b = random.choice(basetime)
s = random.choice(sleeptime)
if scale == 'small':
s *= 1
b *= 0.25
m *= 0.75
if scale == 'midium':
s *= 6
b *= 0.75
m *= 0.75
if scale == 'large':
s *= 12
b *= 1
m *= 1
time.sleep(b+m*s)
def print_html(self):
print(self.response.content.decode('utf8'))
def resolve_page(self):
selector = etree.HTML(self.response.content)
text = selector.xpath('//*[@id="queryListForm"]/div[@class="main"]/div[@class="container padding_top"]/div[@class="row"]/div[@class="col-lg-12"]/div/div/div/text()')
#for i, t in enumerate(text):
# print(i, t.encode('latin_1').decode('utf8'))
text = text[1].encode('latin_1', errors='ignore').decode('utf8', errors='ignore')
print(text)
self.tasklog.log(mode='manual', in_log = 'task resolved: '+ text)
text = re.sub(r'[\s共筆分頁,]', r'', text)
print(text)
self.totalCount, self.totalPage = [int(t) for t in text.split('、')]
def h3_info_collector(self, pageStart, pageEnd):
item_count = 0
for self.pageNow in range(pageStart, pageEnd+1):
self.this_round_time_start()
if self.pageNow > 1:
self.set_form_data_url1(mode = 1, currentPage = self.pageNow)
else:
self.set_form_data_url1(mode = 0)
self.proxy_monitor()
self.first_connection()
for self.pageItem, o in enumerate(self.oncontextmenu, 1):
self.get_banKey_objectId(o)
self.second_connection()
if not self.get_h3():
continue
#parser = parser_cmpy_type(self.h3_query)
parser = self.parser[self.h3_query]
if self.h3_text not in self.objidlog:
self.objidlog[self.h3_text] = set()
self.objidlog[self.h3_text].add(self.objectId)
#if len(self.objectId[self.h3_text]) >= 1000:
# continue
if self.h3_text not in self.tr:
trset = parser.retrive_tr(self.response, set(),
{'banNo':str(self.banNo),
'brBanNo':str(self.brBanNo),
'banKey':str(self.banKey),
'estbId':str(self.estbId),
'objectId':str(self.objectId)},
{'page':str(self.pageNow),
'item':str(self.pageItem)})
else:
trset = parser.retrive_tr(self.response, self.tr[self.h3_text],
{'banNo':str(self.banNo),
'brBanNo':str(self.brBanNo),
'banKey':str(self.banKey),
'estbId':str(self.estbId),
'objectId':str(self.objectId)},
{'page':str(self.pageNow),
'item':str(self.pageItem)})
# self.tr[self.h3_text] = set()
#trset = parser.retrive_tr(self.response, self.tr[self.h3_text], self.h3_text)
if self.h3_text not in self.tr:
self.tr[self.h3_text] = trset
if self.h3_text not in self.trlog:
self.trlog[self.h3_text] = dict()
for s in trset:
if s not in self.trlog[self.h3_text]:
(self.trlog[self.h3_text])[s] = (self.banNo if self.banNo != '' else( self.brBanNo if self.brBanNo != '' else self.estbId))
else:
self.tr[self.h3_text] |= trset
#del parser
self.random_sleep(scale = self.sleep_scale)
else:
item_count += self.pageItem
#self.this_round_time_end()
#self.this_round_exectime()
self.tasklog.log(mode='format', args=(self.exectime(), self.this_round_exectime(), self.pageNow, self.pageItem), postfix = 'page finished, total {: >6d} items'.format(item_count))
print('==================================================')
print('page', self.pageNow, 'total', item_count , ' time', self.exectime(), 'round time', self.this_round_exectime())
print('==================================================')
if item_count >= self.flush_threshold:
#print('end of h3_info_collector', ' total: ', t, ' pages: ', p)
print('end of h3_info_collector() pages:{} items:{}'.format(self.pageNow, item_count))
self.tasklog.log(mode='manual', in_log = 'end of h3_info_collector() pages:{} items:{}'.format(self.pageNow, item_count))
return
def second_page_not_found(self):
selector = etree.HTML(crawler.response.content)
texts = selector.xpath('//table/tr/td/table/tr/td/descendant::*/text()')
clean_texts = list()
for t in texts:
#t = t.encode('latin_1', errors='ignore').decode('utf8', errors='ignore')
t = re.sub(r'\s', r'', t)
if t:
clean_texts.append(t)
else:
if '很抱歉,您所存取的網頁系統暫時無法回應。' in clean_texts and '回上一頁' in clean_texts and '回首頁' in clean_texts:
return True
else:
return False
def output_files(self, itemStart, itemEnd):
d = datetime.now()
timestamp = "{0:0>4d}{1:0>2d}{2:0>2d}_{3:0>2d}{4:0>2d}{5:0>2d}".format(d.year,d.month,d.day,d.hour,d.minute,d.second)
fname = '{0: >5s}@{1: >10s}-{2: >17s}'.format(self.qryCond, str(self.qryType[0]),timestamp)
#fname = '{0: >5s}@{1: >10s} [{2: >6d}-{3: >6d}][{4: >6d}-{5: >6d}]-{6: >17s}'.format(self.qryCond, str(self.qryType[0]), self.pageStart, self.pageEnd, itemStart, itemEnd,timestamp)
for key in self.results:
if self.results[key]:
#j = json.dumps(self.results[key], ensure_ascii=False)
j = self.results[key]
#with open(fname+'_'+key+'_json.json', 'w') as jout:
# json.dump(j, jout, ensure_ascii=False)
with open(self.total_json_name+'_json.json', 'a') as tjout:
json.dump(j, tjout, ensure_ascii=False)
tjout.write(',\n')
#with open(fname+'_'+key+'_json.pkl', 'wb') as jpklout:
# pickle.dump(j, jpklout)
#df = pd.DataFrame(self.results[key])
#with open(fname+'_'+key+'df.csv', 'w') as dfcsvout:
# df.to_csv(dfcsvout, index=False)
#with open(fname+'_'+key+'df.pkl', 'wb') as dfpklout:
# pickle.dump(j, dfpklout)
#with open(fname+'_'+key+'content.html', 'w') as contentout:
# contentout.write(self.response.content.decode('utf8'))
# #pickle.dump(self.response.content.decode('utf8'), contentout)
def set_pageStart(self, pageStart):
self.pageStart = pageStart
def set_pageEnd(self, pageEnd):
self.pageEnd = pageEnd
def parse_and_gen_schema(self, pageStart=1, pageEnd=1):
self.set_pageStart(pageStart)
self.set_pageEnd(pageEnd)
item_count = 0
item_last = 0
item_count_flush = 0
for self.pageNow in range(self.pageStart, self.pageEnd+1):
self.this_round_time_start()
#self.pageNow = p
if self.pageNow > 1:
self.set_form_data_url1(mode = 1, currentPage = self.pageNow)
else:
self.set_form_data_url1(mode = 0)
# 在first_connection刷完一頁(20筆),檢查一次是否超過self.proxy_tick,若是就關掉舊的session,並轉到proxy
self.proxy_monitor()
# self.first_connection() 出問題時重試10次
retry = 0
while not self.first_connection():
if retry > 10:
with open('skip_query.log', 'a') as skpf:
skpf.write(self.qryCond+str(self.qryType)+'\n')
continue
retry += 1
self.tasklog.log(mode='manual', in_log = 'first_connection() @ page{} failed, retry {} times'.format(self.pageNow, retry))
time.sleep(2)
for self.pageItem, o in enumerate(self.oncontextmenu, 1):
#self.pageItem = i
self.get_banKey_objectId(o)
retry = 0
# self.second_connection()
while not self.second_connection():
if retry > 10:
continue
retry += 1
self.tasklog.log(mode='manual', in_log = 'second_connection() @ page{} item {} failed, retry {} times'.format(self.pageNow, self.pageItem, retry))
time.sleep(10)
if self.second_page_not_found():
# 如果第二層商登資料網頁不存在,跳過
self.tasklog.log(mode='format', args=(self.exectime(), self.this_round_exectime(), self.pageNow, self.pageItem), postfix = 'second page not found')
continue
self.get_h3()
#parser = parser_cmpy_type(self.h3_query)
parser = self.parser[self.h3_query]
parser.init_data_schema()
# 改掉log的方式
parser.parser(self.response,
{'banNo':str(self.banNo),
'brBanNo':str(self.brBanNo),
'banKey':str(self.banKey),
'estbId':str(self.estbId),
'objectId':str(self.objectId)},
{'page':str(self.pageNow),
'item':str(self.pageItem)})
#self.end = time.time()
self.exectime(self.h3_query)
print(self.h3_query, parser.data_schema)
#self.results[self.h3_query].append(parser.data_schema)
# add some task info
parser.data_schema['qryCond'] = self.qryCond
parser.data_schema['h3_query'] = self.h3_query
parser.data_schema['pageNow'] = self.pageNow
parser.data_schema['pageItem'] = self.pageItem