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
# -*- coding:utf-8 -*-
# @Time : 2019/8/19 16:51
# @Author : litao
import argparse, datetime, json, os
from multiprocessing import Pool
from crawler.crawler_sys.utils import trans_format
from crawler.crawler_sys.framework.platform_crawler_register import get_crawler
from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan
import logging
from write_data_into_es.func_get_releaser_id import *
parser = argparse.ArgumentParser(description='get releaser follow number')
parser.add_argument('-p', '--process_num', default=10, help=('process num'),type=int)
parser.add_argument('-pl', '--platform', default=[], action='append',
help=('Pass platform names, they will be assembled in python list.'))
args = parser.parse_args()
processes_num = args.process_num
# es = Elasticsearch(hosts='192.168.17.11', port=80,
# http_auth=('crawler', 'XBcasfo8dgfs'))
hosts = '192.168.17.11'
port = 80
user = 'litao'
passwd = 'lQSmSEnGZZxl'
http_auth = (user, passwd)
es = Elasticsearch(hosts=hosts, port=port, http_auth=http_auth)
write_index = "releaser_fans"
write_type = "doc"
def bulk_to_es(single_data):
bulk_all_body = ""
error_info = ""
try:
_id = single_data["releaser_id_str"] + "_" + str(int(
datetime.datetime(year=single_data["data_year"], month=single_data["data_month"],
day=single_data["data_day"]).timestamp() * 1e3))
except:
releaser_id = get_releaser_id(platform=single_data['platform'], releaserUrl=single_data[
'releaserUrl'])
single_data['releaser_id_str'] = single_data['platform'] + "_" + releaser_id
_id = single_data["releaser_id_str"] + "_" + str(int(
datetime.datetime(year=single_data["data_year"], month=single_data["data_month"],
day=single_data["data_day"]).timestamp() * 1e3))
bulk_head = '{"index": {"_id":"%s"}}' % _id
bulk_body = json.dumps(single_data, ensure_ascii=False)
bulk_one_body = bulk_head + '\n' + bulk_body + '\n'
bulk_all_body += bulk_one_body
eror_dic = es.bulk(index=write_index, doc_type=write_type,
body=bulk_all_body, request_timeout=200)
bulk_all_body = ''
if eror_dic['errors'] is True:
count_false = 1
print(eror_dic['items'])
print(bulk_all_body)
error_info += eror_dic['items']
def write_fans_monthly():
now = datetime.datetime.now()
print(now.day)
bulk_all_body = ""
error_info = ""
if now.day == 1:
this_mon = now.month
this_year = now.year
last_month = this_mon - 1 if this_mon >= 2 else 12
last_year = this_year if last_month != 12 else this_year - 1
search_body = {
"query": {
"bool": {
"filter": [
{"term": {"data_year": last_year}},
{"term": {"data_month": last_month}},
], "must": [{"exists": {"field": "releaser_followers_count"}}]
}}
}
res_scan = scan(client=es, query=search_body, index="releaser_fans_monthly", doc_type="doc")
for count_true,data in enumerate(res_scan):
data["_source"]["data_month"] = this_mon
data["_source"]["data_year"] = this_year
if data["_source"]["platform"] == "weibo":
data["_source"]["UID"] = data["_source"]["releaser_id_str"]
try:
_id = data["_source"]["releaser_id_str"] + "_" + str(int(
datetime.datetime(year=this_year, month=this_mon,
day=1).timestamp() * 1e3))
except:
_id = data["_source"]["releaser"] + "_" + str(int(
datetime.datetime(year=this_year, month=this_mon,
day=1).timestamp() * 1e3))
bulk_head = '{"index": {"_id":"%s"}}' % _id
bulk_body = json.dumps(data["_source"], ensure_ascii=False)
bulk_one_body = bulk_head + '\n' + bulk_body + '\n'
bulk_all_body += bulk_one_body
count_true += 1
if count_true % 500 == 0:
eror_dic = es.bulk(index="releaser_fans_monthly", doc_type="doc",
body=bulk_all_body, request_timeout=200)
if eror_dic['errors'] is True:
count_false = 1
print(eror_dic['items'])
print(bulk_all_body)
error_info += eror_dic['items']
print(count_true)
bulk_all_body = ''
if bulk_all_body != '':
eror_dic = es.bulk(index="releaser_fans_monthly", doc_type="doc",
body=bulk_all_body, request_timeout=200)
if eror_dic['errors'] is True:
count_false = 1
print(eror_dic)
error_info += eror_dic['items']
print(count_true)
def write_fans_to_target_doc(read_index=None, read_doc=None, write_index=None, write_doc=None, platform_list=None,
day=15, all_time_doc_id=False, monthly_doc_id=False,scroll="50m"):
count_true = 0
error_info = ""
bulk_all_body = ""
douyin_search_body = {
"query": {
"bool": {
"filter": [
# {"term": {"platform.keyword": "kwai"}},
# {"term": {"releaser_id_str": "kwai_3xcurnwdxabnn5w"}},
{"range": {"fetch_time": {"gte": int(
(datetime.datetime.now() - datetime.timedelta(days=day)).timestamp() * 1e3)}}}
], "must": [{"exists": {"field": "releaser_followers_count"}}]
}},"sort": [
{
"fetch_time": {
"order": "asc"
}
}
]
}
if platform_list:
douyin_search_body["query"]["bool"]["filter"].append({"terms": {"platform.keyword": platform_list}})
douyin_seacn = scan(client=es, query=douyin_search_body, index=read_index, doc_type=read_doc,preserve_order=True,scroll=scroll)
for single_res in douyin_seacn:
try:
releaser = single_res["_source"]["releaser"]
platform = single_res["_source"]["platform"]
releaserUrl = single_res["_source"].get("releaserUrl")
releaser_id_str = single_res["_source"].get("releaser_id_str")
releaser_followers_count = int(single_res["_source"].get("releaser_followers_count"))
timestamp = int(datetime.datetime.now().timestamp() * 1e3)
fetch_time = single_res["_source"]["fetch_time"]
now = datetime.datetime.fromtimestamp(fetch_time / 1000)
except Exception as e:
print(e)
continue
data_day = now.day
data_month = now.month
data_year = now.year
bulk_dic = {
"releaser": releaser,
"platform": platform,
"releaserUrl": releaserUrl,
"releaser_id_str": releaser_id_str,
"releaser_followers_count": releaser_followers_count,
"timestamp": timestamp,
"fetch_time": fetch_time,
"data_day": data_day,
"data_month": data_month,
"data_year": data_year
}
if all_time_doc_id:
_id = releaser_id_str
elif monthly_doc_id:
if not releaser_id_str:
_id = releaser + "_" + str(int(
datetime.datetime(year=bulk_dic["data_year"], month=bulk_dic["data_month"],
day=1).timestamp() * 1e3))
else:
_id = releaser_id_str + "_" + str(int(
datetime.datetime(year=data_year, month=data_month,
day=1).timestamp() * 1e3))
else:
if not releaser_id_str:
_id = releaser + "_" + str(int(
datetime.datetime(year=bulk_dic["data_year"], month=bulk_dic["data_month"],
day=bulk_dic["data_day"]).timestamp() * 1e3))
else:
_id = releaser_id_str + "_" + str(int(
datetime.datetime(year=data_year, month=data_month,
day=data_day).timestamp() * 1e3))
if not _id:
continue
if bulk_dic["platform"] == "weibo":
bulk_dic["UID"] = bulk_dic["releaser_id_str"]
bulk_head = '{"index": {"_id":"%s"}}' % _id
bulk_body = json.dumps(bulk_dic, ensure_ascii=False)
bulk_one_body = bulk_head + '\n' + bulk_body + '\n'
bulk_all_body += bulk_one_body
count_true += 1
if count_true % 1000 == 0:
eror_dic = es.bulk(index=write_index, doc_type=write_doc,
body=bulk_all_body, request_timeout=200)
if eror_dic['errors'] is True:
count_false = 1
print(eror_dic['items'])
print(bulk_all_body)
print(count_true)
bulk_all_body = ''
if bulk_all_body != '':
eror_dic = es.bulk(index=write_index, doc_type=write_doc,
body=bulk_all_body, request_timeout=200)
if eror_dic['errors'] is True:
count_false = 1
print(eror_dic)
print(count_true)
def weibo_fans():
pass
def get_target_releasers(platform=None):
releasers_dic = {}
search_body = {
"query": {
"bool": {
"filter": [
# {"term": {"platform.keyword": "kwai"}}
], "must": [{"exists": {"field": "releaser_id_str"}}]
}
}
}
if platform:
search_body["query"]["bool"]["filter"].append({"terms": {"platform.keyword": platform}})
res_scan = scan(client=es, query=search_body, index="target_releasers", doc_type="doc")
for res in res_scan:
try:
res["_source"].pop("is_purchased",0)
except:
pass
if res["_source"].get("platform") in releasers_dic:
releasers_dic[res["_source"].get("platform")].append(res["_source"])
else:
releasers_dic[res["_source"].get("platform")] = []
releasers_dic[res["_source"].get("platform")].append(res["_source"])
return releasers_dic
def get_releaser_follower_num(line, get_crawler):
releaserUrl = line['releaserUrl']
platform = line['platform']
crawler_initialization = get_crawler(platform)
try:
now = datetime.datetime.now()
crawler = crawler_initialization().get_releaser_follower_num
follower_num, releaser_img = crawler(releaserUrl)
line['releaser_followers_count'] = follower_num
line['releaser_img'] = releaser_img
line["fetch_time"] = int(now.timestamp() * 1e3)
line["data_day"] = now.day
line["data_month"] = now.month
line["data_year"] = now.year
# print(line['releaserUrl'], line['platform'], line['releaser_followers_count'],releaser_img)
if line['releaser_followers_count'] is None:
return None
bulk_to_es(line)
except Exception as e:
print(e)
print(platform + " " + releaserUrl + ", faile to get fans num")
if __name__ == "__main__":
try:
if not args.platform:
write_fans_monthly()
write_fans_to_target_doc(read_index="short-video-production", read_doc="daily-url",
write_index=write_index, write_doc=write_type,
platform_list=["抖音", "haokan", "腾讯新闻","kwai","miaopai"], day=4)
write_fans_to_target_doc(read_index="releaser_fans", read_doc="doc", write_index="releaser_fans_monthly",
write_doc="doc", day=7, monthly_doc_id=True)
write_fans_to_target_doc(read_index="releaser_fans", read_doc="doc", write_index="releaser_fans_latest",
write_doc="doc", day=7, all_time_doc_id=True)
except:
pass
try:
pool = Pool(processes=processes_num)
releasers_dic = get_target_releasers(platform=args.platform)
print("get data")
while releasers_dic:
for platform in releasers_dic:
if len(releasers_dic[platform]) == 0:
releasers_dic.pop(platform,0)
break
line = releasers_dic[platform].pop()
# print(line['releaserUrl'], line['platform'])
# get_releaser_follower_num(line, get_crawler)
pool.apply_async(func=get_releaser_follower_num, args=(line, get_crawler))
pool.close()
pool.join()
except:
pass
finally:
write_fans_monthly()
write_fans_to_target_doc(read_index="releaser_fans", read_doc="doc", write_index="releaser_fans_latest",
write_doc="doc", day=5, all_time_doc_id=True)
write_fans_to_target_doc(read_index="releaser_fans", read_doc="doc", write_index="releaser_fans_monthly",
write_doc="doc", day=10, monthly_doc_id=True)
# write_fans_monthly()
# write_fans_to_target_doc(read_index="releaser_fans", read_doc="doc", write_index="releaser_fans_monthly",
# write_doc="doc", day=10, monthly_doc_id=True)
# releaser_dic = get_target_releasers()
# for platforn in releaser_dic:
# for line in releaser_dic[platforn]:
# get_releaser_follower_num(line,get_crawler)
# fn = r"D:\work_file\5月补数据.csv"
# with open(fn, 'r', encoding='gb18030')as f:
# head = f.readline()
# head_list = head.strip().split(',')
# for i in f:
# print("\n")
# line_dict = {}
# line_list = i.strip().split(',')
# test_dict = dict(zip(head_list, line_list))
# get_releaser_follower_num(test_dict, get_crawler)
# write_fans_to_target_doc(read_index="short-video-daily-url-2019", read_doc="daily-url", write_index=write_index,
# write_doc=write_type, platform_list=["抖音", "haokan", "腾讯新闻"], day=8)
# write_fans_to_target_doc(read_index="releaser_fans", read_doc="doc", write_index="short_video_fans_latest",
# write_doc="doc", day=6, all_time_doc_id=True)