-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconn_sql_server.py
More file actions
1279 lines (1090 loc) · 53.6 KB
/
Copy pathconn_sql_server.py
File metadata and controls
1279 lines (1090 loc) · 53.6 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/11/17 15:05
# @Author : GuoChang
# @Site : https://github.com/xiphodon
# @File : conn_sql_server.py
# @Software: PyCharm
import pymssql
import settings
import time
import company_spider_3
import company_spider_4
import company_spider_5
import company_spider_6
import json
import merge_all_spider_data
import rakuten_spider_7
import company_spider_9
import rakuten_spider_10
import os
import datetime
import requests
# # settings.py 文件
# host = '192.168.19.110'
# user = 'sasa'
# password = 'sasa19990909!@#'
# database = 'LTCYT'
# charset = 'utf8'
def save_to_sql_server():
"""
存数据至sql——server
:return:
"""
conn = pymssql.connect(host=settings.host, user=settings.user, password=settings.password,
database=settings.database, charset=settings.charset)
cur = conn.cursor()
if not cur:
raise (NameError, "数据库连接失败")
else:
print('数据库连接成功')
# save_spider_3_data_to_db(conn, cur)
# save_spider_4_data_to_db(conn, cur)
# save_spider_5_data_to_db(conn, cur)
# save_spider_6_data_to_db(conn, cur)
# save_spider_all_data_to_db(conn, cur)
# save_rakuten_spider_shop_info_to_db(conn, cur)
# save_rakuten_spider_products_info_to_db(conn, cur)
# save_rakuten_spider_finally_shop_to_db(conn, cur)
# google_key insert
# save_google_key_to_db(conn, cur)
check_del_google_key_to_db(conn, cur)
# save_rakuten_spider_key_to_db(conn, cur)
# save_kompass_company_spider_to_db(conn, cur)
conn.close()
def check_del_google_key_to_db(conn, cur):
"""
检查
:param conn:
:param cur:
:return:
"""
headers = {
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
'Connection': 'keep-alive'
}
def check_google_key(google_key, sleep_time=0.0):
"""
检查googlekey是否可用
:return:
"""
time.sleep(sleep_time)
# google_key = 'AIzaSyAUsnERWvgUrNKQy4YvHAaeg99HdhJLpTM'
result = requests.get(f'https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
f'location=-33.8670522,151.1957362&radius=5000&types=food'
f'&key={google_key}', headers=headers)
status = json.loads(result.text).get('status').strip()
print(status)
if status == 'OK':
return True
else:
return False
# check google key流程
sql_str = 'select ID, Name, CreateTime from GoogleKey'
cur.execute(sql_str.encode('utf8'))
server_google_key_tuple = cur.fetchall()
delete_count = 0
for item_data in server_google_key_tuple:
print(f'=========={item_data}===============')
item_data_id = item_data[0]
item_data_google_key = item_data[1]
try:
if check_google_key(item_data_google_key, sleep_time=0.2) \
and check_google_key(item_data_google_key, sleep_time=0.25):
print(f'{item_data} --- OK')
else:
if check_google_key(item_data_google_key, sleep_time=0.25):
continue
# delete this data
sql_del_str = f'DELETE FROM GoogleKey WHERE ID = {item_data_id}'
cur.execute(sql_del_str)
conn.commit()
delete_count += 1
print(f'delete ---- {sql_del_str}')
except Exception as e:
print(f'--- error --- {e}')
print(f'delete count: {delete_count}')
# 更新后再次统计数量
sql_str = 'select ID, Name, CreateTime from GoogleKey'
cur.execute(sql_str.encode('utf8'))
server_google_key_tuple = cur.fetchall()
print(f'valid key count: {len(server_google_key_tuple)}')
def save_google_key_to_db(conn, cur):
"""
保存google key 到数据库
:param conn:
:param cur:
:return:
"""
# 获取本地key集
json_path = r'C:\Users\topeasecpb\Desktop\googlekey\all_valid_google_key_list_3.json'
with open(json_path, 'r', encoding='utf8') as fp:
data = json.load(fp)
# 获取服务器key集
sql_str = 'select Name from GoogleKey'
cur.execute(sql_str.encode('utf8'))
server_google_key_tuple = cur.fetchall()
server_google_key_list = [i[0] for i in server_google_key_tuple]
print(f'data_len: {len(data)}')
print(f'server_data_len: {len(server_google_key_list)}')
# 去重
new_google_key_set = set(data) - set(server_google_key_list)
print(f'new_key_len: {len(new_google_key_set)}')
# 可用新集
new_data = list(new_google_key_set)
for item_key in new_data:
try:
create_time = datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
sql_str = "insert into GoogleKey(Name, CreateTime) values(N'%s',N'%s')" % (item_key, create_time)
cur.execute(sql_str.encode('utf8'))
conn.commit()
print(sql_str)
except Exception as e:
print(f'--------- error --------- {e}')
break
def save_rakuten_spider_shop_info_to_db(conn, cur):
"""
存储乐天spider商家信息至数据库
:param conn:
:param cur:
:return:
"""
data = rakuten_spider_7.read_shop_info_json()
print('data', 'OK')
cur.execute("select top 1 company_md5 from rakuten_company_2018_05 order by id desc")
server_company_md5 = cur.fetchone()
print(server_company_md5)
is_find = False
if server_company_md5 is None:
is_find = True
error_count = 0
count = 0
for item_dict in data:
company_md5 = item_dict.get('company_md5', '').replace("'", "''")
if not is_find:
if company_md5 == server_company_md5[0]:
# print(company_md5)
is_find = True
continue
else:
continue
company_href = item_dict.get('company_href', '').replace("'", "''")
company_name = item_dict.get('company_name', '').replace("'", "''")
company_address = item_dict.get('company_address', '').replace("'", "''")
company_tel = item_dict.get('company_tel', '').replace("'", "''")
company_fax = item_dict.get('company_fax', '').replace("'", "''")
company_representative = item_dict.get('company_representative', '').replace("'", "''")
company_operator = item_dict.get('company_operator', '').replace("'", "''")
company_security_officer = item_dict.get('company_security_officer', '').replace("'", "''")
company_email = item_dict.get('company_email', '').replace("'", "''")
sql_str = None
try:
sql_str = "insert into rakuten_company_2018_05(company_md5,company_href,company_name," \
"company_address,company_tel,company_fax," \
"company_representative,company_operator,company_security_officer,company_email)" \
" values(N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s')" \
% (company_md5, company_href, company_name, company_address, company_tel, company_fax, company_representative,
company_operator, company_security_officer, company_email)
cur.execute(sql_str.encode('utf8'))
conn.commit()
count += 1
print(company_md5, 'OK', ',当前 count:', count, ', error_count:', error_count)
# time.sleep(0.005)
except Exception as e:
error_count += 1
print(e, error_count, company_md5, '===================')
print(sql_str)
print(len(company_md5))
print(len(company_href))
print(len(company_name))
print(len(company_address))
print(len(company_tel))
print(len(company_fax))
print(len(company_representative))
print(len(company_operator))
print(len(company_security_officer))
print(len(company_email))
# raise e
# break
# conn.commit()
print('count:', count, ', error_count:', error_count)
def save_rakuten_spider_products_info_to_db(conn, cur):
"""
存储乐天spider产品信息至数据库
:param conn:
:param cur:
:return:
"""
data = rakuten_spider_7.read_products_json()
print('data', 'OK')
cur.execute("select top 1 product_href from rakuten_product_2018_05 order by id desc")
server_product_href = cur.fetchone()
print(server_product_href)
is_find = False
if server_product_href is None:
is_find = True
error_count = 0
count = 0
for item_dict in data:
product_href = item_dict.get('product_href', '').replace("'", "''")
if not is_find:
if product_href == server_product_href[0]:
# print(company_md5)
is_find = True
continue
else:
continue
shop_md5 = item_dict.get('shop_md5', '').replace("'", "''")
shop_name = item_dict.get('shop_name', '').replace("'", "''")
shop_href = item_dict.get('shop_href', '').replace("'", "''")
product_title = item_dict.get('product_title', '').replace("'", "''")
product_price = item_dict.get('product_price', '').replace("'", "''")
product_score = item_dict.get('product_score', '').replace("'", "''")
product_legend = item_dict.get('product_legend', '').replace("'", "''")
product_type_first = item_dict.get('product_type_first', '').replace("'", "''")
product_type_second = item_dict.get('product_type_second', '').replace("'", "''")
sql_str = None
try:
sql_str = "insert into rakuten_product_2018_05(shop_name,shop_href,product_title," \
"product_href,product_price," \
"product_score,product_legend,product_type_first,product_type_second,shop_md5)" \
" values(N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s')" \
% (shop_name, shop_href, product_title, product_href, product_price, product_score,
product_legend, product_type_first, product_type_second, shop_md5)
cur.execute(sql_str.encode('utf8'))
conn.commit()
count += 1
print(product_href, 'OK', ',当前 count:', count, ', error_count:', error_count)
# time.sleep(0.005)
except Exception as e:
error_count += 1
print(e, error_count, product_href, '===================')
print(sql_str)
print(len(shop_name))
print(len(shop_href))
print(len(product_title))
print(len(product_href))
print(len(product_price))
print(len(product_score))
print(len(product_legend))
print(len(product_type_first))
print(len(product_type_second))
print(len(shop_md5))
# raise e
# break
# conn.commit()
print('count:', count, ', error_count:', error_count)
def save_rakuten_spider_key_to_db(conn, cur):
"""
乐天数据(根据关键字爬取)导入数据库
:param conn:
:param cur:
:return:
"""
rakuten_spider = rakuten_spider_10.Main().spider
data_path = os.path.join(rakuten_spider.settings.key_json_dir_path, 'shop_info_list.json')
with open(data_path, 'r', encoding='utf8') as fp:
data = json.load(fp)
key_word_list = rakuten_spider.settings.key_word_list
error_insert_count = 0
error_update_count = 0
insert_count = 0
update_count = 0
count = 0
for item_dict in data:
# 查这一家店是否已存储
# 已存储:读出,查询关键字列表是否出现在company_product_desc字段,
# 若有则什么也不做,若无则添加新关键字至该字段,并更新数据(更新时间)
# 未存储:直接插库
print('=' * 30)
company_website = item_dict.get('company_website', '').replace("'", "''")
company_website = str(company_website).strip()
if company_website == '':
continue
# [id], \
# [company_name], \
# [company_product_type], \
# [company_product_desc], \
# [company_address], \
# [company_website], \
# [company_tel], \
# [company_fax], \
# [company_email], \
# [company_representative], \
# [company_operator], \
# [company_security_officer], \
# [create_datetime], \
# [update_datetime], \
# [update_version]
cur.execute("select top 1 [id], [company_name], [company_product_type], "
"[company_product_desc], [company_address], [company_website], [company_tel], "
"[company_fax], [company_email], [company_representative], [company_operator], "
"[company_security_officer], [create_datetime], [update_datetime], [update_version] "
"from ffd_cbec_company where data_origin_id='1' and company_website=N'%s'"
% (company_website,))
server_data = cur.fetchone()
company_country_id = 103
company_product_desc = ','.join(key_word_list)
company_product_type = ''
company_name = item_dict.get('company_name', '').replace("'", "''")
company_address = item_dict.get('company_address', '').replace("'", "''")
company_tel = item_dict.get('company_tel', '').replace("'", "''")
company_fax = item_dict.get('company_fax', '').replace("'", "''")
company_representative = item_dict.get('company_representative', '').replace("'", "''")
company_operator = item_dict.get('company_operator', '').replace("'", "''")
company_security_officer = item_dict.get('company_security_officer', '').replace("'", "''")
company_email = item_dict.get('company_email', '').replace("'", "''")
data_origin_id = 1 # rakuten
create_datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
update_datetime = create_datetime
update_version = 1
if server_data is None:
# 这一家数据库不存在
# 直接插库
# print(f'new data, server DB has not this data: {company_website}')
if str(company_name).strip() == '':
continue
sql_str = None
try:
sql_str = "insert into ffd_cbec_company(data_origin_id,company_website,company_product_desc, " \
"company_product_type, company_name, company_address, company_tel, company_fax," \
"company_representative, company_operator, company_security_officer, company_email," \
"create_datetime, update_datetime, update_version, company_country_id)" \
" values(N'%d',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s'," \
"N'%s',N'%s',N'%s',N'%d')" \
% (data_origin_id, company_website, company_product_desc, company_product_type,
company_name, company_address, company_tel, company_fax, company_representative,
company_operator, company_security_officer, company_email, create_datetime,
update_datetime, update_version, company_country_id)
cur.execute(sql_str.encode('utf8'))
conn.commit()
insert_count += 1
count += 1
print(f'insert {company_website} OK, now insert_count:{insert_count}, '
f'error_insert_count:{error_insert_count}')
# time.sleep(0.005)
except Exception as e:
error_insert_count += 1
print(e, error_insert_count, company_website, '++++++ insert error ++++++')
print(sql_str)
# break
else:
# 这一家在数据库
# 查询关键字列表是否出现在company_product_desc字段,若有则什么也不做
# print(f'old data, server DB has this data: {company_website}')
server_company_product_desc = server_data[3]
is_server_company_product_desc_has_key_word = False
for item_key in key_word_list:
if item_key in str(server_company_product_desc).split(','):
is_server_company_product_desc_has_key_word = True
break
# if str(server_company_product_desc).find(item_key) >= 0:
# is_server_company_product_desc_has_key_word = True
# break
if is_server_company_product_desc_has_key_word:
# 服务器重复数据中已包含现关键词
print('pass')
# print(f'do nothing, server data has this key word')
continue
else:
# 服务器重复数据中不包含现关键词,添加新关键字至该字段,并更新数据(更新联系方式、时间)
# print(item_dict)
# print(server_data)
server_id = server_data[0]
server_company_name = server_data[1].replace("'", "''")
server_company_product_type = server_data[2].replace("'", "''")
server_company_product_desc = server_data[3].replace("'", "''")
server_company_address = server_data[4].replace("'", "''")
# server_company_website = server_data[5].replace("'", "''")
server_company_tel = server_data[6].replace("'", "''")
server_company_fax = server_data[7].replace("'", "''")
server_company_email = server_data[8].replace("'", "''")
server_company_representative = server_data[9].replace("'", "''")
server_company_operator = server_data[10].replace("'", "''")
server_company_security_officer = server_data[11].replace("'", "''")
# server_create_datetime = server_data[12]
# server_update_datetime = server_data[13]
server_update_version = server_data[14]
# 更新旧数据字段
company_name = comparison_between_old_and_new_data(server_company_name, company_name)
company_product_type = comparison_between_old_and_new_data(server_company_product_type,
company_product_type)
company_product_desc = f'{server_company_product_desc},{company_product_desc}'.strip(',')
company_address = comparison_between_old_and_new_data(server_company_address, company_address)
# company_website = comparison_between_old_and_new_data(server_company_website, company_website)
company_tel = comparison_between_old_and_new_data(server_company_tel, company_tel)
company_fax = comparison_between_old_and_new_data(server_company_fax, company_fax)
company_email = rakuten_merge_email(server_company_email, company_email)
company_representative = comparison_between_old_and_new_data(server_company_representative,
company_representative)
company_operator = comparison_between_old_and_new_data(server_company_operator, company_operator)
company_security_officer = comparison_between_old_and_new_data(server_company_security_officer,
company_security_officer)
# create_datetime = server_create_datetime
update_datetime = update_datetime
update_version = int(server_update_version) + 1 if server_update_version is not None else 2
sql_str = None
try:
sql_str = f"update ffd_cbec_company set " \
f"company_name=N'{company_name}', " \
f"company_product_type=N'{company_product_type}', " \
f"company_product_desc=N'{company_product_desc}', " \
f"company_address=N'{company_address}', " \
f"company_tel=N'{company_tel}', " \
f"company_fax=N'{company_fax}', " \
f"company_email=N'{company_email}', " \
f"company_representative=N'{company_representative}', " \
f"company_operator=N'{company_operator}', " \
f"company_security_officer=N'{company_security_officer}', " \
f"update_datetime=N'{update_datetime}', " \
f"update_version=N'{update_version}' " \
f"where id={server_id}"
# print(sql_str)
cur.execute(sql_str.encode('utf8'))
conn.commit()
update_count += 1
count += 1
print(f'update {company_website} OK, now update_count:{update_count}, '
f'error_update_count:{error_update_count}')
except Exception as e:
error_update_count += 1
print(e, error_update_count, company_website, '++++++ update error ++++++')
print(sql_str)
print(server_id)
# break
# break
print(f'count:{count}, insert_conut:{insert_count}, update_count:{update_count}, '
f'error_insert_count:{error_insert_count}, error_update_count:{error_update_count}')
def comparison_between_old_and_new_data(old_value, new_value):
"""
新旧数据对比,优先选择有值数据
:param old_value: 服务器端旧数据
:param new_value: 新采集数据
:return:
"""
return old_value if new_value is None or new_value == '' else new_value
def rakuten_merge_email(old_value, new_value):
"""
乐天,合并邮箱字段
:param old_value:
:param new_value:
:return:
"""
if old_value is None:
old_value = ''
if new_value is None:
new_value = ''
return ','.join(set(f'{old_value},{new_value}'.split(',')))
def save_rakuten_spider_finally_shop_to_db(conn, cur):
"""
乐天数据整合商店公司库至数据库
:param conn:
:param cur:
:return:
"""
data = rakuten_spider_7.read_finally_shop_info_json()
print('data', 'OK')
cur.execute("select top 1 company_website from ffd_cbec_company where data_origin_id='1' order by id desc")
server_company_website = cur.fetchone()
print(server_company_website)
is_find = False
if server_company_website is None:
is_find = True
error_count = 0
count = 0
for item_dict in data:
company_website = item_dict.get('company_website', '').replace("'", "''")
if not is_find:
if company_website == server_company_website[0]:
# print(company_md5)
is_find = True
continue
else:
continue
data_origin_id = '1'
company_product_desc = item_dict.get('company_product_desc', '').replace("'", "''")
company_product_type = item_dict.get('company_product_type', '').replace("'", "''")
company_name = item_dict.get('company_name', '').replace("'", "''")
company_address = item_dict.get('company_address', '').replace("'", "''")
company_tel = item_dict.get('company_tel', '').replace("'", "''")
company_fax = item_dict.get('company_fax', '').replace("'", "''")
company_representative = item_dict.get('company_representative', '').replace("'", "''")
company_operator = item_dict.get('company_operator', '').replace("'", "''")
company_security_officer = item_dict.get('company_security_officer', '').replace("'", "''")
company_email = item_dict.get('company_email', '').replace("'", "''")
sql_str = None
try:
sql_str = "insert into ffd_cbec_company(data_origin_id,company_website,company_product_desc, " \
"company_product_type, company_name, company_address, company_tel, company_fax," \
"company_representative, company_operator, company_security_officer, company_email)" \
" values(N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s')" \
% (data_origin_id, company_website, company_product_desc, company_product_type,
company_name, company_address,
company_tel, company_fax, company_representative, company_operator,
company_security_officer, company_email)
cur.execute(sql_str.encode('utf8'))
conn.commit()
count += 1
print(company_website, 'OK', ',当前 count:', count, ', error_count:', error_count)
# time.sleep(0.005)
except Exception as e:
error_count += 1
print(e, error_count, company_website, '===================')
print(sql_str)
print(len(company_website))
print(len(company_product_desc))
print(len(company_product_type))
print(len(company_name))
print(len(company_address))
print(len(company_tel))
print(len(company_fax))
print(len(company_representative))
print(len(company_operator))
print(len(company_security_officer))
print(len(company_email))
# raise e
# break
# conn.commit()
print('count:', count, ', error_count:', error_count)
def save_spider_all_data_to_db(conn, cur):
"""
存储spider所有数据至数据库
:return:
"""
data = merge_all_spider_data.read_all_company_json()
print('data OK **************')
error_count = 0
cur.execute("select top 1 company_id from Company3 order by ID desc")
last_company_id_int = cur.fetchone()
is_find = False
if last_company_id_int is None:
is_find = True
count = 0
for item_dict in data:
item_dict = check_dict(item_dict)
company_id = int(item_dict.get('company_id', ''))
# if company_id != 1000189:
# continue
# print(item_dict)
if not is_find:
if company_id == last_company_id_int[0]:
print(company_id)
is_find = True
continue
else:
continue
Industry = item_dict.get('Industry', '').replace("'", "''")
Name = item_dict.get('Name', '').replace("'", "''")
Introduction = item_dict.get('Introduction', '').replace("'", "''")
Description = item_dict.get('Description', '').replace("'", "''")
Description_cn = item_dict.get('Description_cn', '').replace("'", "''")
Country = item_dict.get('Country', '').replace("'", "''")
Country_cn = item_dict.get('Country_cn', '').replace("'", "''")
City = item_dict.get('City', '').replace("'", "''")
Address = item_dict.get('Address', '').replace("'", "''")
Website = item_dict.get('Website', '').replace("'", "''")
MainProduct = item_dict.get('MainProduct', '').replace("'", "''")
Email = item_dict.get('Email', '').replace("'", "''")
Fax = item_dict.get('Fax', '').replace("'", "''")
Telephone = item_dict.get('Telephone', '').replace("'", "''")
CustomerPhone = item_dict.get('CustomerPhone', '').replace("'", "''")
SalesVolume = item_dict.get('SalesVolume', '').replace("'", "''")
MainMarkets = item_dict.get('MainMarkets', '').replace("'", "''")
PostCode = item_dict.get('PostCode', '').replace("'", "''")
BusinessType = item_dict.get('BusinessType', '').replace("'", "''")
YearStartExporting = item_dict.get('YearStartExporting', '').replace("'", "''")
ContactPerson = item_dict.get('ContactPerson', '').replace("'", "''")
JobTitle = item_dict.get('JobTitle', '').replace("'", "''")
OfficeAddress_Detail = item_dict.get('OfficeAddress_Detail', '').replace("'", "''")
Department = item_dict.get('Department', '').replace("'", "''")
TradeCapacity = item_dict.get('TradeCapacity', '').replace("'", "''")
ProductionCapacity = item_dict.get('ProductionCapacity', '').replace("'", "''")
AverageLeadTime = item_dict.get('AverageLeadTime', '').replace("'", "''")
ContractManufacturing = item_dict.get('ContractManufacturing', '').replace("'", "''")
RegisteredCapital = item_dict.get('RegisteredCapital', '').replace("'", "''")
RDCapacity = item_dict.get('RDCapacity', '').replace("'", "''")
LegalRepresentative = item_dict.get('LegalRepresentative', '').replace("'", "''")
QCStaff = item_dict.get('QCStaff', '').replace("'", "''")
QualityControl = item_dict.get('QualityControl', '').replace("'", "''")
YearEstablished = item_dict.get('YearEstablished', '').replace("'", "''")
Certificates = item_dict.get('Certificates', '').replace("'", "''")
Revenue = item_dict.get('Revenue', '').replace("'", "''")
NumberOfEmployess = item_dict.get('NumberOfEmployess', '').replace("'", "''")
PurchaseProduct = item_dict.get('PurchaseProduct', '').replace("'", "''")
Type = 'buyer or seller'
try:
sql_str = "insert into Company3(company_id,Industry,Name,Introduction,Description,Description_cn,Country," \
"Country_cn,City,Address,Website," \
"MainProduct,Email,Fax,Telephone,CustomerPhone,SalesVolume,MainMarkets,PostCode,BusinessType," \
"YearStartExporting,ContactPerson,JobTitle,OfficeAddress_Detail,Department,TradeCapacity," \
"ProductionCapacity,AverageLeadTime,ContractManufacturing,RegisteredCapital,RDCapacity," \
"LegalRepresentative,QCStaff,QualityControl,YearEstablished,Certificates,Revenue," \
"NumberOfEmployess,PurchaseProduct,Type) values(N'%d',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s', \
N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s', N'%s',N'%s',\
N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s', \
N'%s',N'%s',N'%s')" \
% (company_id, Industry, Name, Introduction, Description, Description_cn, Country, Country_cn,
City, Address, Website, MainProduct, Email, Fax, Telephone, CustomerPhone, SalesVolume,
MainMarkets, PostCode, BusinessType, YearStartExporting, ContactPerson, JobTitle,
OfficeAddress_Detail, Department, TradeCapacity, ProductionCapacity,AverageLeadTime,
ContractManufacturing, RegisteredCapital, RDCapacity, LegalRepresentative, QCStaff,
QualityControl, YearEstablished, Certificates, Revenue, NumberOfEmployess, PurchaseProduct,
Type)
cur.execute(sql_str.encode('utf8'))
conn.commit()
count += 1
print(company_id, 'OK', ',当前 count:', count, ', error_count:', error_count)
except Exception as e:
error_count += 1
print(e, error_count, company_id, '===================')
# raise e
# finally:
# print(json.dumps(item_dict))
# break
# conn.commit()
print('count:', count, ', error_count:', error_count)
def save_spider_3_data_to_db(conn, cur):
"""
存储spider3数据至数据库
:return:
"""
data_3 = company_spider_3.read_company_desc_list_has_web_json()
print('data OK **************')
error_count = 0
cur.execute("select top 1 company_id from Company0 order by ID desc")
last_company_id_int = cur.fetchone()
is_find = False
if last_company_id_int is None:
is_find = True
count = 0
for item_dict in data_3:
item_dict = check_dict(item_dict)
company_id = int(item_dict.get('company_id', ''))
####################################################################
# if company_id != 121332:
# continue
# print(item_dict)
if not is_find:
if company_id == last_company_id_int[0]:
print(company_id)
is_find = True
continue
else:
continue
####################################################################
Name = item_dict.get('company_name', '').replace("'", "''")
Description = item_dict.get('company_description', '').replace("'", "''")
Country = item_dict.get('company_country', '').replace("'", "''")
City = item_dict.get('company_city', '').replace("'", "''")
Address = item_dict.get('company_adrress', '').replace("'", "''")
Website = item_dict.get('company_web_origin', '').replace("'", "''")
MainProduct = item_dict.get('company_product', '').replace("'", "''")
Telephone = item_dict.get('company_telephone', '').replace("'", "''")
Type = 'buyer or seller'
try:
sql_str = "insert into Company0(company_id,Name,Description,Country,City,Address,Website," +\
"MainProduct,Telephone,Type) values(N'%d',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s')"\
% (company_id, Name, Description, Country, City, Address, Website, MainProduct, Telephone, Type)
cur.execute(sql_str.encode('utf8'))
conn.commit()
count += 1
print(company_id, 'OK', ',当前 count:', count, ', error_count:', error_count)
# time.sleep(0.005)
except Exception as e:
error_count += 1
print(e, error_count, company_id, '===================')
# raise e
# conn.commit()
print('count:', count, ', error_count:', error_count)
def save_spider_4_data_to_db(conn, cur):
"""
存储spider4数据至数据库
:return:
"""
data_4 = company_spider_4.read_company_desc_has_phone_str_json()
print('data OK **************')
base_company_id = 1000 * 10000
error_count = 0
cur.execute("select top 1 company_id from Company0 order by ID desc")
last_company_id_int = cur.fetchone()
is_find = False
if last_company_id_int is None:
is_find = True
elif last_company_id_int[0] < base_company_id:
is_find = True
count = 0
for item_dict in data_4:
item_dict = check_dict(item_dict)
company_id = int(item_dict.get('company_id', '')) + base_company_id
# if company_id != 1000189:
# continue
# print(item_dict)
if not is_find:
if company_id == last_company_id_int[0]:
print(company_id)
is_find = True
continue
else:
continue
Name = item_dict.get('company_name', '').replace("'", "''")
Description = item_dict.get('company_desc', '').replace("'", "''")
Country = item_dict.get('Country/Region', '').replace("'", "''")
City = item_dict.get('Location', '').replace("'", "''")
Address = item_dict.get('Address', '').replace("'", "''")
Website = item_dict.get('Website', '').replace("'", "''")
MainProduct = item_dict.get('Main Products', '').replace("'", "''")
Fax = item_dict.get('Fax Number', '').replace("'", "''")
Telephone = item_dict.get('Telephone', '').replace("'", "''")
CustomerPhone = item_dict.get('Mobilephone', '').replace("'", "''")
SalesVolume = item_dict.get('Total Annual Sales Volume', '').replace("'", "''")
MainMarkets = item_dict.get('Main Markets', '').replace("'", "''")
PostCode = item_dict.get('Zip/Post Code', '').replace("'", "''")
BusinessType = item_dict.get('Business Type', '').replace("'", "''")
YearStartExporting = item_dict.get('Year Start Exporting', '').replace("'", "''")
ContactPerson = item_dict.get('Contact Person', '').replace("'", "''")
JobTitle = item_dict.get('Job Title', '').replace("'", "''")
OfficeAddress_Detail = item_dict.get('Operational Address', '').replace("'", "''")
Department = item_dict.get('Department', '').replace("'", "''")
TradeCapacity = item_dict.get('Trade Capacity', '').replace("'", "''")
ProductionCapacity = item_dict.get('Production Capacity', '').replace("'", "''")
AverageLeadTime = item_dict.get('Average Lead Time', '').replace("'", "''")
ContractManufacturing = item_dict.get('Contract Manufacturing', '').replace("'", "''")
RegisteredCapital = item_dict.get('Registered Capital', '').replace("'", "''")
RDCapacity = item_dict.get('R&D; Capacity', '').replace("'", "''")
LegalRepresentative = item_dict.get('Legal Representative / CEO', '').replace("'", "''")
QCStaff = item_dict.get('No. of QC Staff', '').replace("'", "''")
QualityControl = item_dict.get('Quality Control', '').replace("'", "''")
YearEstablished = item_dict.get('Year Established', '').replace("'", "''")
Certificates = item_dict.get('Certificates', '').replace("'", "''")
Revenue = item_dict.get('Total Revenue', '').replace("'", "''")
NumberOfEmployess = item_dict.get('Number Of Employess', '').replace("'", "''")
Type = 'buyer or seller'
try:
sql_str = "insert into Company0(company_id,Name,Description,Country,City,Address,Website," \
"MainProduct,Fax,Telephone,CustomerPhone,SalesVolume,MainMarkets,PostCode,BusinessType," \
"YearStartExporting,ContactPerson,JobTitle,OfficeAddress_Detail,Department,TradeCapacity," \
"ProductionCapacity,AverageLeadTime,ContractManufacturing,RegisteredCapital,RDCapacity," \
"LegalRepresentative,QCStaff,QualityControl,YearEstablished,Certificates,Revenue," \
"NumberOfEmployess,Type) values(N'%d',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s'," \
"N'%s',N'%s',N'%s',N'%s', \
N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s'," \
"N'%s',N'%s',N'%s',N'%s',N'%s',N'%s', \
N'%s',N'%s',N'%s')" \
% (company_id, Name, Description, Country, City, Address, Website, MainProduct, Fax, Telephone,
CustomerPhone, SalesVolume, MainMarkets, PostCode, BusinessType, YearStartExporting,
ContactPerson, JobTitle, OfficeAddress_Detail, Department, TradeCapacity, ProductionCapacity,
AverageLeadTime, ContractManufacturing, RegisteredCapital, RDCapacity, LegalRepresentative,
QCStaff, QualityControl, YearEstablished, Certificates, Revenue, NumberOfEmployess, Type)
cur.execute(sql_str.encode('utf8'))
conn.commit()
count += 1
print(company_id, 'OK', ',当前 count:', count, ', error_count:', error_count)
except Exception as e:
error_count += 1
print(e, error_count, company_id, '===================')
# raise e
# finally:
# print(json.dumps(item_dict))
# break
# conn.commit()
print('count:', count, ', error_count:', error_count)
def save_spider_5_data_to_db(conn, cur):
"""
存储spider5数据至数据库
:return:
"""
data_5 = company_spider_5.read_company_desc_list_json()
print('data OK **************')
base_company_id = 2000 * 10000
error_count = 0
cur.execute("SELECT TOP 1 company_id FROM Company0 ORDER BY ID DESC")
last_company_id_int = cur.fetchone()
is_find = False
if last_company_id_int is None:
is_find = True
elif last_company_id_int[0] < base_company_id:
is_find = True
count = 0
for item_dict in data_5:
item_dict = check_dict(item_dict)
company_id = int(item_dict.get('company_id', '')) + base_company_id
# if company_id != 1000189:
# continue
# print(item_dict)
if not is_find:
if company_id == last_company_id_int[0]:
print(company_id)
is_find = True
continue
else:
continue
Industry = item_dict.get('category', '').replace("'", "''")
Name = item_dict.get('company_name', '').replace("'", "''")
Introduction = item_dict.get('company_introduction', '').replace("'", "''")
Description = item_dict.get('company_desc_en', '').replace("'", "''")
Description_cn = item_dict.get('company_desc_cn', '').replace("'", "''")
Country = item_dict.get('country_or_area_en', '').replace("'", "''")
Country_cn = item_dict.get('country_or_area_cn', '').replace("'", "''")
Address = item_dict.get('company_address', '').replace("'", "''")
Website = item_dict.get('company_web', '').replace("'", "''")
Email = item_dict.get('company_email', '').replace("'", "''")
Fax = item_dict.get('company_fax', '').replace("'", "''")
Telephone = item_dict.get('company_telephone', '').replace("'", "''")
PostCode = item_dict.get('post_code', '').replace("'", "''")
ContactPerson = item_dict.get('contact_person', '').replace("'", "''")
NumberOfEmployess = item_dict.get('employee_count', '').replace("'", "''")
Type = 'buyer'
try:
sql_str = "insert into Company0(company_id,Industry,Name,Introduction,Description,Description_cn," \
"Country,Country_cn,Address,Website,Email,Fax,Telephone,PostCode,ContactPerson," \
"NumberOfEmployess,Type) values(N'%d',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s'," \
"N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s',N'%s')" \
% (company_id, Industry, Name, Introduction, Description, Description_cn, Country, Country_cn,
Address, Website, Email, Fax, Telephone, PostCode, ContactPerson, NumberOfEmployess, Type)
cur.execute(sql_str.encode('utf8'))
conn.commit()
count += 1
print(company_id, 'OK', ',当前 count:', count, ', error_count:', error_count)
except Exception as e:
error_count += 1
print(e, error_count, company_id, '===================')
# raise e
# finally:
# print(json.dumps(item_dict))
# break
# conn.commit()
print('count:', count, ', error_count:', error_count)