-
Notifications
You must be signed in to change notification settings - Fork 905
Expand file tree
/
Copy pathweibo.py
More file actions
executable file
·3574 lines (3192 loc) · 151 KB
/
Copy pathweibo.py
File metadata and controls
executable file
·3574 lines (3192 loc) · 151 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 -*-
import codecs
import copy
import csv
import json
import logging
import logging.config
import math
import os
import random
import re
import sqlite3
import sys
import time
import warnings
import webbrowser
from collections import OrderedDict
from datetime import date, datetime, timedelta
from pathlib import Path
from time import sleep
from urllib.parse import parse_qs, unquote, urlparse
import requests
from requests.exceptions import RequestException
from lxml import etree
import json5
from requests.adapters import HTTPAdapter
from tqdm import tqdm
import const
from util import csvutil
from util.dateutil import convert_to_days_ago
from util.notify import push_deer
from util.llm_analyzer import LLMAnalyzer # 导入 LLM 分析器
import piexif
warnings.filterwarnings("ignore")
# 如果日志文件夹不存在,则创建
if not os.path.isdir("log/"):
os.makedirs("log/")
logging_path = os.path.split(os.path.realpath(__file__))[0] + os.sep + "logging.conf"
logging.config.fileConfig(logging_path)
logger = logging.getLogger("weibo")
# 日期时间格式
DTFORMAT = "%Y-%m-%dT%H:%M:%S"
class Weibo(object):
def __init__(self, config):
"""Weibo类初始化"""
self.validate_config(config)
self.only_crawl_original = config["only_crawl_original"] # 取值范围为0、1,程序默认值为0,代表要爬取用户的全部微博,1代表只爬取用户的原创微博
self.remove_html_tag = config[
"remove_html_tag"
] # 取值范围为0、1, 0代表不移除微博中的html tag, 1代表移除
since_date = config["since_date"]
# since_date 若为整数,则取该天数之前的日期;若为 yyyy-mm-dd,则增加时间
if isinstance(since_date, int):
since_date = date.today() - timedelta(since_date)
since_date = since_date.strftime(DTFORMAT)
elif self.is_date(since_date):
since_date = "{}T00:00:00".format(since_date)
elif self.is_datetime(since_date):
pass
else:
logger.error("since_date 格式不正确,请确认配置是否正确")
sys.exit()
self.since_date = since_date # 起始时间,即爬取发布日期从该值到现在的微博,形式为yyyy-mm-ddThh:mm:ss,如:2023-08-21T09:23:03
end_date = config.get("end_date", "")
# end_date 为空字符串时不限制截止时间
if end_date:
if isinstance(end_date, int):
end_date = date.today() - timedelta(end_date)
end_date = end_date.strftime(DTFORMAT)
elif self.is_date(end_date):
end_date = "{}T23:59:59".format(end_date)
elif self.is_datetime(end_date):
pass
else:
logger.error("end_date 格式不正确,请确认配置是否正确")
sys.exit()
self.end_date = end_date # 截止时间,为空则不限制
self.start_page = config.get("start_page", 1) # 开始爬的页,如果中途被限制而结束可以用此定义开始页码
self.write_mode = config[
"write_mode"
] # 结果信息保存类型,为list形式,可包含csv、mongo和mysql三种类型
self.markdown_split_by = config.get("markdown_split_by", "day") # markdown文件分割方式,day/day_by_month/month/year/all
self.original_pic_download = config[
"original_pic_download"
] # 取值范围为0、1, 0代表不下载原创微博图片,1代表下载
self.retweet_pic_download = config[
"retweet_pic_download"
] # 取值范围为0、1, 0代表不下载转发微博图片,1代表下载
self.original_video_download = config[
"original_video_download"
] # 取值范围为0、1, 0代表不下载原创微博视频,1代表下载
self.retweet_video_download = config[
"retweet_video_download"
] # 取值范围为0、1, 0代表不下载转发微博视频,1代表下载
# 新增Live Photo视频下载配置
self.original_live_photo_download = config.get("original_live_photo_download", 0)
self.retweet_live_photo_download = config.get("retweet_live_photo_download", 0)
self.download_comment = config["download_comment"] # 1代表下载评论,0代表不下载
self.comment_max_download_count = config[
"comment_max_download_count"
] # 如果设置了下评论,每条微博评论数会限制在这个值内
self.comment_pic_download = config.get("comment_pic_download", 0) # 1代表下载评论图片,0代表不下载
self.download_repost = config["download_repost"] # 1代表下载转发,0代表不下载
self.repost_max_download_count = config[
"repost_max_download_count"
] # 如果设置了下转发,每条微博转发数会限制在这个值内
self.user_id_as_folder_name = config.get(
"user_id_as_folder_name", 0
) # 结果目录名,取值为0或1,决定结果文件存储在用户昵称文件夹里还是用户id文件夹里
self.write_time_in_exif = config.get(
"write_time_in_exif", 0
) # 是否开启微博时间写入EXIF,取值范围为0、1, 0代表不开启, 1代表开启
self.change_file_time = config.get(
"change_file_time", 0
) # 是否修改文件时间,取值范围为0、1, 0代表不开启, 1代表开启
self.output_directory = config.get(
"output_directory", "weibo"
) # 输出目录配置,默认为"weibo"
# Cookie支持:优先使用环境变量WEIBO_COOKIE,其次使用config.json中的配置
cookie_config = config.get("cookie")
cookie_string = os.environ.get("WEIBO_COOKIE") or cookie_config
self.cookie_file_path = None
if isinstance(cookie_config, str) and cookie_config.endswith('.txt'):
self.cookie_file_path = cookie_config
if os.path.isfile(self.cookie_file_path):
with open(self.cookie_file_path, 'r', encoding='utf-8') as f:
cookie_string = f.read().strip()
logger.info(f"从Cookie文件 {self.cookie_file_path} 读取Cookie")
else:
logger.warning(f"Cookie文件 {self.cookie_file_path} 不存在,将使用默认空Cookie")
cookie_string = ""
elif os.environ.get("WEIBO_COOKIE"):
logger.info("使用环境变量WEIBO_COOKIE中的Cookie")
core_cookies = {} # 核心包
backup_cookies = {} # 备份
# Cookie清洗:提取核心字段。若后续预热失败,则回退使用原版 _T_WM/XSRF-TOKEN
if cookie_string and "SUB=" in cookie_string:
# 1. 提取核心 SUB
match_sub = re.search(r'SUB=(.*?)(;|$)', cookie_string)
if match_sub:
core_cookies['SUB'] = match_sub.group(1)
# 2. 提取备份指纹
match_twm = re.search(r'_T_WM=(.*?)(;|$)', cookie_string)
if match_twm:
backup_cookies['_T_WM'] = match_twm.group(1)
match_xsrf = re.search(r'XSRF-TOKEN=(.*?)(;|$)', cookie_string)
if match_xsrf:
backup_cookies['XSRF-TOKEN'] = match_xsrf.group(1)
# 保底:如果没有提取到 SUB,说明格式特殊,全量加载
if not core_cookies and cookie_string:
for pair in cookie_string.split(';'):
if '=' in pair:
key, value = pair.split('=', 1)
core_cookies[key.strip()] = value.strip()
self.headers = {
'Referer': 'https://m.weibo.cn/', # 修正 Referer 为 m.weibo.cn
'accept': 'application/json, text/plain, */*',
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
'cache-control': 'max-age=0',
'priority': 'u=0, i',
'sec-ch-ua': '"Chromium";v="136", "Microsoft Edge";v="136", "Not.A/Brand";v="99"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'same-origin',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0',
}
self.mysql_config = config.get("mysql_config") # MySQL数据库连接配置,可以不填
self.mongodb_URI = config.get("mongodb_URI") # MongoDB数据库连接字符串,可以不填
self.post_config = config.get("post_config") # post_config,可以不填
self.page_weibo_count = config.get("page_weibo_count") # page_weibo_count,爬取一页的微博数,默认10页
self.sqlite_db_path = config.get("sqlite_db_path", "weibodata.db") # SQLite数据库路径
# 初始化 LLM 分析器
self.llm_analyzer = LLMAnalyzer(config) if config.get("llm_config") else None
user_id_list = config["user_id_list"]
requests_session = requests.Session()
requests_session.cookies.update(core_cookies)
self.session = requests_session
try:
# 请求只带 SUB
# 服务器下发适配 m.weibo.cn 的新指纹
self.session.get("https://m.weibo.cn", headers=self.headers, timeout=10)
logger.info("Session 预热成功,服务器已下发最新指纹。")
except Exception as e:
#请求失败时,启用备份
logger.warning(f"Session 预热失败 ({e}),正在启用备份 Cookie...")
self.session.cookies.update(backup_cookies) # 把旧指纹装进去救急
adapter = HTTPAdapter(max_retries=5)
self.session.mount('http://', adapter)
self.session.mount('https://', adapter)
# 避免卡住
if isinstance(user_id_list, list):
random.shuffle(user_id_list)
query_list = config.get("query_list") or []
if isinstance(query_list, str):
query_list = query_list.split(",")
self.query_list = query_list
if not isinstance(user_id_list, list):
if not os.path.isabs(user_id_list):
user_id_list = (
os.path.split(os.path.realpath(__file__))[0] + os.sep + user_id_list
)
self.user_config_file_path = user_id_list # 用户配置文件路径
user_config_list = self.get_user_config_list(user_id_list)
else:
self.user_config_file_path = ""
user_config_list = [
{
"user_id": user_id,
"since_date": self.since_date,
"end_date": self.end_date,
"query_list": query_list,
}
for user_id in user_id_list
]
self.user_config_list = user_config_list # 要爬取的微博用户的user_config列表
self.user_config = {} # 用户配置,包含用户id和since_date
self.start_date = "" # 获取用户第一条微博时的日期
self.query = ""
self.user = {} # 存储目标微博用户信息
self.got_count = 0 # 存储爬取到的微博数
self.weibo = [] # 存储爬取到的所有微博信息
self.weibo_id_list = [] # 存储爬取到的所有微博id
self.long_sleep_count_before_each_user = 0 #每个用户前的长时间sleep避免被ban
self.store_binary_in_sqlite = config.get("store_binary_in_sqlite", 0)
# 防封禁配置初始化
self.anti_ban_config = config.get("anti_ban_config", {})
self.anti_ban_enabled = self.anti_ban_config.get("enabled", False)
# 爬取状态跟踪
self.crawl_stats = {
"weibo_count": 0, # 已爬取微博数
"request_count": 0, # 已发送请求数
"api_errors": 0, # API错误数
"start_time": None, # 开始时间
"batch_count": 0, # 当前批次计数
"last_batch_time": None # 上次批次时间
}
def calculate_dynamic_delay(self):
"""计算动态延迟时间"""
if not self.anti_ban_enabled:
return 0
config = self.anti_ban_config
base_delay = config.get("request_delay_min", 8)
# 根据请求次数增加延迟
request_count = self.crawl_stats["request_count"]
if request_count > 100:
base_delay += 5
if request_count > 300:
base_delay += 10
# 根据爬取时间增加延迟
if self.crawl_stats["start_time"]:
time_elapsed = time.time() - self.crawl_stats["start_time"]
if time_elapsed > 300: # 5分钟
base_delay += 5
# 随机波动
max_delay = config.get("request_delay_max", 15)
return random.uniform(base_delay, max_delay)
def should_pause_session(self):
"""检查是否应该暂停当前会话"""
if not self.anti_ban_enabled:
return False, ""
config = self.anti_ban_config
current_time = time.time()
# 条件1:达到数量阈值
max_weibo = config.get("max_weibo_per_session", 500)
if self.crawl_stats["weibo_count"] >= max_weibo:
return True, f"达到单次运行最大微博数({max_weibo})"
# 条件2:运行时间过长
if self.crawl_stats["start_time"]:
session_time = current_time - self.crawl_stats["start_time"]
max_time = config.get("max_session_time", 600)
if session_time > max_time:
return True, f"单次运行时间过长({int(session_time)}秒)"
# 条件3:API错误率过高
max_errors = config.get("max_api_errors", 5)
if self.crawl_stats["api_errors"] >= max_errors:
return True, f"API错误过多({self.crawl_stats['api_errors']}次)"
# 条件4:随机概率(模拟用户休息)
random_prob = config.get("random_rest_probability", 0.01)
if random.random() < random_prob:
return True, "随机休息"
return False, ""
def check_batch_delay(self):
"""检查是否需要批次延迟"""
if not self.anti_ban_enabled:
return
config = self.anti_ban_config
batch_size = config.get("batch_size", 50)
batch_delay = config.get("batch_delay", 30)
# 检查是否达到批次大小
if self.crawl_stats["batch_count"] >= batch_size:
current_time = time.time()
# 检查距离上次批次的时间
if self.crawl_stats["last_batch_time"]:
time_since_last_batch = current_time - self.crawl_stats["last_batch_time"]
if time_since_last_batch < batch_delay:
# 如果距离上次批次时间太短,等待补足
wait_time = batch_delay - time_since_last_batch
logger.info(f"批次延迟: 等待 {wait_time:.1f} 秒")
sleep(wait_time)
logger.info(f"批次延迟: 等待 {batch_delay} 秒")
sleep(batch_delay)
# 重置批次计数
self.crawl_stats["batch_count"] = 0
self.crawl_stats["last_batch_time"] = time.time()
def get_random_headers(self):
"""获取随机请求头"""
if not self.anti_ban_enabled:
return self.headers
config = self.anti_ban_config
# 随机选择User-Agent
user_agents = config.get("user_agents", [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0"
])
user_agent = random.choice(user_agents)
# 随机选择Accept-Language
accept_languages = config.get("accept_languages", [
"zh-CN,zh;q=0.9,en;q=0.8"
])
accept_language = random.choice(accept_languages)
# 随机选择Referer
referers = config.get("referer_list", [
"https://m.weibo.cn/",
"https://weibo.com/"
])
referer = random.choice(referers)
# 返回随机化的请求头
return {
'Referer': referer,
'accept': 'application/json, text/plain, */*',
'accept-language': accept_language,
'cache-control': 'max-age=0',
'priority': 'u=0, i',
'sec-ch-ua': '"Chromium";v="136", "Microsoft Edge";v="136", "Not.A/Brand";v="99"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'same-origin',
'upgrade-insecure-requests': '1',
'user-agent': user_agent,
}
def update_crawl_stats(self, weibo_count=0, request_count=0, api_error=False):
"""更新爬取统计"""
if not self.anti_ban_enabled:
return
if weibo_count > 0:
self.crawl_stats["weibo_count"] += weibo_count
self.crawl_stats["batch_count"] += weibo_count
if request_count > 0:
self.crawl_stats["request_count"] += request_count
if api_error:
self.crawl_stats["api_errors"] += 1
def reset_crawl_stats(self):
"""重置爬取统计(休息后调用)"""
self.crawl_stats = {
"weibo_count": 0,
"request_count": 0,
"api_errors": 0,
"start_time": time.time(),
"batch_count": 0,
"last_batch_time": None
}
logger.info("爬取统计已重置,继续爬取")
def perform_anti_ban_rest(self):
"""执行防封禁休息"""
if not self.anti_ban_enabled:
return
config = self.anti_ban_config
rest_time_min = config.get("rest_time_min", 600)
# 添加随机波动(±10%)
rest_time = int(rest_time_min * random.uniform(0.9, 1.1))
logger.info("┌────────────────────────────────────┐")
logger.info("│ 🛡️ 防封禁休息中... │")
logger.info("│ 休息时间: %-4d 秒 │", rest_time)
logger.info("│ 预计恢复: %s │",
(datetime.now() + timedelta(seconds=rest_time)).strftime("%H:%M:%S"))
logger.info("└────────────────────────────────────┘")
# 执行休息
sleep(rest_time)
logger.info("休息结束,继续爬取微博")
def validate_config(self, config):
"""验证配置是否正确"""
# 验证如下1/0相关值
argument_list = [
"only_crawl_original",
"original_pic_download",
"retweet_pic_download",
"original_video_download",
"retweet_video_download",
"original_live_photo_download",
"retweet_live_photo_download",
"download_comment",
"download_repost",
]
for argument in argument_list:
# 使用 get() 获取值,新增字段默认为0
value = config.get(argument, 0)
if value != 0 and value != 1:
logger.warning("%s值应为0或1,请重新输入", argument)
sys.exit()
# 验证query_list
query_list = config.get("query_list") or []
if (not isinstance(query_list, list)) and (not isinstance(query_list, str)):
logger.warning("query_list值应为list类型或字符串,请重新输入")
sys.exit()
# 验证write_mode
write_mode = ["csv", "json", "mongo", "mysql", "sqlite", "post", "markdown"]
if not isinstance(config["write_mode"], list):
sys.exit("write_mode值应为list类型")
for mode in config["write_mode"]:
if mode not in write_mode:
logger.warning(
"%s为无效模式,请从csv、json、mongo、mysql、sqlite、post、markdown中挑选一个或多个作为write_mode", mode
)
sys.exit()
# 验证运行模式
if "sqlite" not in config["write_mode"] and const.MODE == "append":
logger.warning("append模式下请将sqlite加入write_mode中")
sys.exit()
# 验证markdown_split_by
markdown_split_by = config.get("markdown_split_by", "day")
if markdown_split_by not in ["day", "day_by_month", "month", "year", "all"]:
logger.warning("markdown_split_by值应为day、day_by_month、month、year或all,请重新输入")
sys.exit()
# 验证user_id_list
user_id_list = config["user_id_list"]
if (not isinstance(user_id_list, list)) and (not user_id_list.endswith(".txt")):
logger.warning("user_id_list值应为list类型或txt文件路径")
sys.exit()
if not isinstance(user_id_list, list):
if not os.path.isabs(user_id_list):
user_id_list = (
os.path.split(os.path.realpath(__file__))[0] + os.sep + user_id_list
)
if not os.path.isfile(user_id_list):
logger.warning("不存在%s文件", user_id_list)
sys.exit()
# 验证since_date
since_date = config["since_date"]
if (not isinstance(since_date, int)) and (not self.is_datetime(since_date)) and (not self.is_date(since_date)):
logger.warning("since_date值应为yyyy-mm-dd形式、yyyy-mm-ddTHH:MM:SS形式或整数,请重新输入")
sys.exit()
# 验证end_date
end_date = config.get("end_date", "")
if end_date:
if (not isinstance(end_date, int)) and (not self.is_datetime(end_date)) and (not self.is_date(end_date)):
logger.warning("end_date值应为yyyy-mm-dd形式、yyyy-mm-ddTHH:MM:SS形式或整数,请重新输入")
sys.exit()
comment_max_count = config["comment_max_download_count"]
if not isinstance(comment_max_count, int):
logger.warning("最大下载评论数 (comment_max_download_count) 应为整数类型")
sys.exit()
elif comment_max_count < 0:
logger.warning("最大下载评论数 (comment_max_download_count) 应该为正整数")
sys.exit()
repost_max_count = config["repost_max_download_count"]
if not isinstance(repost_max_count, int):
logger.warning("最大下载转发数 (repost_max_download_count) 应为整数类型")
sys.exit()
elif repost_max_count < 0:
logger.warning("最大下载转发数 (repost_max_download_count) 应该为正整数")
sys.exit()
def is_datetime(self, since_date):
"""判断日期格式是否为 %Y-%m-%dT%H:%M:%S"""
try:
datetime.strptime(since_date, DTFORMAT)
return True
except ValueError:
return False
def is_date(self, since_date):
"""判断日期格式是否为 %Y-%m-%d"""
try:
datetime.strptime(since_date, "%Y-%m-%d")
return True
except ValueError:
return False
def get_json(self, params):
url = "https://m.weibo.cn/api/container/getIndex?"
try:
r = self.session.get(url, params=params, headers=self.headers, verify=False, timeout=10)
r.raise_for_status()
response_json = r.json()
return response_json, r.status_code
except RequestException as e:
logger.error(f"请求失败,错误信息:{e}")
return {}, 500
except ValueError as ve:
logger.error(f"JSON 解码失败,错误信息:{ve}")
return {}, 500
def handle_captcha(self, js):
"""
处理验证码挑战,提示用户手动完成验证。
参数:
js (dict): API 返回的 JSON 数据。
返回:
bool: 如果用户成功完成验证码,返回 True;否则返回 False。
"""
logger.debug(f"收到的 JSON 数据:{js}")
captcha_url = js.get("url")
if captcha_url:
logger.warning("检测到验证码挑战。正在打开验证码页面以供手动验证。")
webbrowser.open(captcha_url)
else:
logger.warning("检测到可能的验证码挑战,但未提供验证码 URL。请手动检查浏览器并完成验证码验证。")
return False
logger.info("请在打开的浏览器窗口中完成验证码验证。")
while True:
try:
# 等待用户输入
user_input = input("完成验证码后,请输入 'y' 继续,或输入 'q' 退出:").strip().lower()
if user_input == 'y':
logger.info("用户输入 'y',继续爬取。")
return True
elif user_input == 'q':
logger.warning("用户选择退出,程序中止。")
sys.exit("用户选择退出,程序中止。")
else:
logger.warning("无效输入,请重新输入 'y' 或 'q'。")
except EOFError:
logger.error("读取用户输入时发生 EOFError,程序退出。")
sys.exit("输入流已关闭,程序中止。")
def get_weibo_json(self, page):
"""获取网页中微博json数据"""
url = "https://m.weibo.cn/api/container/getIndex?"
params = (
{
"container_ext": "profile_uid:" + str(self.user_config["user_id"]),
"containerid": "100103type=401&q=" + self.query,
"page_type": "searchall",
}
if self.query
else {"containerid": "230413" + str(self.user_config["user_id"])}
)
params["page"] = page
params["count"] = self.page_weibo_count
max_retries = 5
retries = 0
backoff_factor = 5
while retries < max_retries:
try:
# 防封禁:使用随机请求头
current_headers = self.get_random_headers()
# 防封禁:动态延迟
delay = self.calculate_dynamic_delay()
if delay > 0:
logger.debug(f"动态延迟: {delay:.1f} 秒")
sleep(delay)
response = self.session.get(url, params=params, headers=current_headers, timeout=10)
response.raise_for_status() # 如果响应状态码不是 200,会抛出 HTTPError
js = response.json()
# 更新统计:成功请求
self.update_crawl_stats(request_count=1)
if 'data' in js:
logger.info(f"成功获取到页面 {page} 的数据。")
return js
else:
logger.warning("未能获取到数据,可能需要验证码验证。")
if self.handle_captcha(js):
logger.info("用户已完成验证码验证,继续请求数据。")
retries = 0 # 重置重试计数器
continue
else:
logger.error("验证码验证失败或未完成,程序将退出。")
sys.exit()
except RequestException as e:
retries += 1
sleep_time = backoff_factor * (2 ** retries)
logger.error(f"请求失败,错误信息:{e}。等待 {sleep_time} 秒后重试...")
sleep(sleep_time)
# 更新统计:API错误
self.update_crawl_stats(api_error=True)
except ValueError as ve:
retries += 1
sleep_time = backoff_factor * (2 ** retries)
logger.error(f"JSON 解码失败,错误信息:{ve}。等待 {sleep_time} 秒后重试...")
sleep(sleep_time)
# 更新统计:API错误
self.update_crawl_stats(api_error=True)
logger.error("超过最大重试次数,跳过当前页面。")
return {}
def user_to_csv(self):
"""将爬取到的用户信息写入csv文件"""
file_dir = os.path.split(os.path.realpath(__file__))[0] + os.sep + self.output_directory
if not os.path.isdir(file_dir):
os.makedirs(file_dir)
file_path = file_dir + os.sep + "users.csv"
self.user_csv_file_path = file_path
result_headers = [
"用户id",
"昵称",
"性别",
"生日",
"所在地",
"IP属地",
"学习经历",
"公司",
"注册时间",
"阳光信用",
"微博数",
"粉丝数",
"关注数",
"简介",
"主页",
"头像",
"高清头像",
"微博等级",
"会员等级",
"是否认证",
"认证类型",
"认证信息",
"上次记录微博信息",
]
result_data = [
[
v.encode("utf-8") if "unicode" in str(type(v)) else v
for v in self.user.values()
]
]
# 已经插入信息的用户无需重复插入,返回的id是空字符串或微博id 发布日期%Y-%m-%d
last_weibo_msg = csvutil.insert_or_update_user(
logger, result_headers, result_data, file_path
)
self.last_weibo_id = last_weibo_msg.split(" ")[0] if last_weibo_msg else ""
self.last_weibo_date = (
last_weibo_msg.split(" ")[1]
if last_weibo_msg
else self.user_config["since_date"]
)
def user_to_mongodb(self):
"""将爬取的用户信息写入MongoDB数据库"""
user_list = [self.user]
self.info_to_mongodb("user", user_list)
logger.info("%s信息写入MongoDB数据库完毕", self.user["screen_name"])
def user_to_mysql(self):
"""将爬取的用户信息写入MySQL数据库"""
mysql_config = {
"host": "localhost",
"port": 3306,
"user": "root",
"password": "123456",
"charset": "utf8mb4",
}
# 创建'weibo'数据库
create_database = """CREATE DATABASE IF NOT EXISTS weibo DEFAULT
CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"""
self.mysql_create_database(mysql_config, create_database)
# 创建'user'表
create_table = """
CREATE TABLE IF NOT EXISTS user (
id varchar(20) NOT NULL,
screen_name varchar(30),
gender varchar(10),
statuses_count INT,
followers_count INT,
follow_count INT,
registration_time varchar(20),
sunshine varchar(20),
birthday varchar(40),
location varchar(200),
ip_location varchar(50),
education varchar(200),
company varchar(200),
description varchar(400),
profile_url varchar(200),
profile_image_url varchar(200),
avatar_hd varchar(200),
urank INT,
mbrank INT,
verified BOOLEAN DEFAULT 0,
verified_type INT,
verified_reason varchar(140),
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"""
self.mysql_create_table(mysql_config, create_table)
self.mysql_insert(mysql_config, "user", [self.user])
logger.info("%s信息写入MySQL数据库完毕", self.user["screen_name"])
def user_to_database(self):
"""将用户信息写入文件/数据库"""
self.user_to_csv()
if "mysql" in self.write_mode:
self.user_to_mysql()
if "mongo" in self.write_mode:
self.user_to_mongodb()
if "sqlite" in self.write_mode:
self.user_to_sqlite()
def get_user_info(self):
"""获取用户信息"""
params = {"containerid": "100505" + str(self.user_config["user_id"])}
url = "https://m.weibo.cn/api/container/getIndex"
# 这里在读取下一个用户的时候很容易被ban,需要优化休眠时长
# 加一个count,不需要一上来啥都没干就sleep
if self.long_sleep_count_before_each_user > 0:
sleep_time = random.randint(30, 60)
# 添加log,否则一般用户不知道以为程序卡了
logger.info(f"""短暂sleep {sleep_time}秒,避免被ban""")
sleep(sleep_time)
logger.info("sleep结束")
self.long_sleep_count_before_each_user = self.long_sleep_count_before_each_user + 1
max_retries = 5 # 设置最大重试次数,避免无限循环
retries = 0
backoff_factor = 5 # 指数退避的基数(秒)
while retries < max_retries:
try:
logger.info(f"准备获取ID:{self.user_config['user_id']}的用户信息第{retries+1}次。")
# 防封禁:使用随机请求头
current_headers = self.get_random_headers()
# 防封禁:动态延迟
delay = self.calculate_dynamic_delay()
if delay > 0:
logger.debug(f"动态延迟: {delay:.1f} 秒")
sleep(delay)
response = self.session.get(url, params=params, headers=current_headers, timeout=10)
response.raise_for_status()
js = response.json()
# 更新统计:成功请求
self.update_crawl_stats(request_count=1)
if 'data' in js and 'userInfo' in js['data']:
info = js["data"]["userInfo"]
user_info = OrderedDict()
user_info["id"] = self.user_config["user_id"]
user_info["screen_name"] = info.get("screen_name", "")
user_info["gender"] = info.get("gender", "")
params = {
"containerid": "230283" + str(self.user_config["user_id"]) + "_-_INFO"
}
zh_list = ["生日", "所在地", "IP属地", "小学", "初中", "高中", "大学", "公司", "注册时间", "阳光信用"]
en_list = [
"birthday",
"location",
"ip_location",
"education",
"education",
"education",
"education",
"company",
"registration_time",
"sunshine",
]
for i in en_list:
user_info[i] = ""
js, _ = self.get_json(params)
if js["ok"]:
cards = js["data"]["cards"]
if isinstance(cards, list) and len(cards) > 1:
card_list = cards[0]["card_group"] + cards[1]["card_group"]
for card in card_list:
if card.get("item_name") in zh_list:
user_info[
en_list[zh_list.index(card.get("item_name"))]
] = card.get("item_content", "")
user_info["statuses_count"] = self.string_to_int(
info.get("statuses_count", 0)
)
user_info["followers_count"] = self.string_to_int(
info.get("followers_count", 0)
)
user_info["follow_count"] = self.string_to_int(info.get("follow_count", 0))
user_info["description"] = info.get("description", "")
user_info["profile_url"] = info.get("profile_url", "")
user_info["profile_image_url"] = info.get("profile_image_url", "")
user_info["avatar_hd"] = info.get("avatar_hd", "")
user_info["urank"] = info.get("urank", 0)
user_info["mbrank"] = info.get("mbrank", 0)
user_info["verified"] = info.get("verified", False)
user_info["verified_type"] = info.get("verified_type", -1)
user_info["verified_reason"] = info.get("verified_reason", "")
self.user = self.standardize_info(user_info)
self.user_to_database()
logger.info(f"成功获取到用户 {self.user_config['user_id']} 的信息。")
return 0
elif isinstance(js.get("url"), str) and js.get("url").strip():
logger.warning("未能获取到用户信息,可能需要验证码验证。")
if self.handle_captcha(js):
logger.info("用户已完成验证码验证,继续请求用户信息。")
retries = 0 # 重置重试计数器
continue
else:
logger.error("验证码验证失败或未完成,程序将退出。")
sys.exit()
elif isinstance(js.get("msg"), str) and "这里还没有内容" in js.get("msg"):
logger.warning("未能获取到用户信息,可能账号已注销或用户id有误。")
return 1
else:
logger.warning("未能获取到用户信息。")
return 1
except RequestException as e:
retries += 1
sleep_time = backoff_factor * (2 ** retries)
logger.error(f"请求失败,错误信息:{e}。等待 {sleep_time} 秒后重试...")
sleep(sleep_time)
# 更新统计:API错误
self.update_crawl_stats(api_error=True)
except ValueError as ve:
retries += 1
sleep_time = backoff_factor * (2 ** retries)
logger.error(f"JSON 解码失败,错误信息:{ve}。等待 {sleep_time} 秒后重试...")
sleep(sleep_time)
# 更新统计:API错误
self.update_crawl_stats(api_error=True)
logger.error("超过最大重试次数,程序将退出。")
sys.exit("超过最大重试次数,程序已退出。")
def get_long_weibo(self, id):
"""获取长微博"""
url = "https://m.weibo.cn/detail/%s" % id
logger.info(f"""URL: {url} """)
for i in range(5):
sleep(random.uniform(1.0, 2.5))
html = self.session.get(url, headers=self.headers, verify=False).text
html = html[html.find('"status":') :]
html = html[: html.rfind('"call"')]
html = html[: html.rfind(",")]
html = "{" + html + "}"
js = json.loads(html, strict=False)
weibo_info = js.get("status")
if weibo_info:
weibo = self.parse_weibo(weibo_info)
return weibo
def get_pics(self, weibo_info):
"""获取微博原始图片url"""
pic_list = []
if weibo_info.get("pics"):
pic_info = weibo_info["pics"]
for pic in pic_info:
if not isinstance(pic, dict) or not pic.get('large'):
continue
# 跳过视频类型(多视频微博中视频以 type=video 存在 pics 中)
if pic.get('type') == 'video':
continue
url = pic['large']['url']
# 将 URL 中的非原图尺寸标识替换为 large,确保获取原图
url = re.sub(
r'/(mw\d+|bmiddle|thumb\d+|orj\d+|woriginal)/',
'/large/', url
)
pic_list.append(url)
# 兼容正文里的“查看图片”类型链接,这类内容有时不落在 pics 数组里
for url in self.get_inline_image_urls(weibo_info):
if url not in pic_list:
pic_list.append(url)
pics = ",".join(pic_list) if pic_list else ""
return pics
def normalize_inline_url(self, href):
"""规范化正文中的跳转链接,优先还原 sinaurl 包裹的真实地址"""
if not href:
return ""
href = href.strip()
if href.startswith("//"):
return "https:" + href
if href.startswith("/"):
return "https://m.weibo.cn" + href
parsed = urlparse(href)
if "sinaurl" in parsed.path:
query = parse_qs(parsed.query)
target = query.get("u", [""])[0]
if target:
return unquote(target)
return href
def is_inline_image_url(self, url):
"""判断正文中的链接是否直接指向图片资源"""
if not url:
return False
lower_url = url.lower().split("?")[0]
return lower_url.endswith((".jpg", ".jpeg", ".png", ".webp", ".gif"))
def get_link_urls(self, selector):
"""获取正文中的普通链接,保留真实 URL 以便后续检索"""
link_urls = []
for a in selector.xpath("//a"):
href = a.xpath("@href")
if not href:
continue
link_text = a.xpath("string(.)").strip()
raw_href = href[0]
# @用户/话题/页内跳转不作为普通链接保存
if raw_href.startswith("/n/") or raw_href.startswith("#"):
continue
if len(link_text) > 2 and link_text[0] == "#" and link_text[-1] == "#":
continue
normalized_url = self.normalize_inline_url(raw_href)
if not normalized_url or self.is_inline_image_url(normalized_url):
continue
if normalized_url not in link_urls:
link_urls.append(normalized_url)
return link_urls
def get_inline_image_urls(self, weibo_info):