-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyzer.py
More file actions
2220 lines (1968 loc) · 101 KB
/
Copy pathanalyzer.py
File metadata and controls
2220 lines (1968 loc) · 101 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 python3
"""
多功能站长工具箱 - 网站分析器
功能:SEO分析、可用性检测、SSL证书检查、批量检测、HTML报告生成
"""
import requests
from bs4 import BeautifulSoup
import ssl
import socket
import subprocess
import time
import json
import sys
import os
import re
import argparse
from datetime import datetime
from urllib.parse import urlparse, urljoin
from concurrent.futures import ThreadPoolExecutor, as_completed
def fix_encoding(response):
"""修复 requests 编码检测不准的问题(常见于百度等中文站点)"""
# 1. 优先从 Content-Type header 获取 charset
content_type = response.headers.get('Content-Type', '')
charset_match = re.search(r'charset=([^\s;]+)', content_type, re.I)
if charset_match:
response.encoding = charset_match.group(1).strip()
return response.text
# 2. 从 HTML 前 2048 字节检测 meta charset
head = response.content[:2048].decode('ascii', errors='ignore')
meta_charset = re.search(r'<meta[^>]+charset=["\']?([^"\'\s;>]+)', head, re.I)
if meta_charset:
response.encoding = meta_charset.group(1)
return response.text
# 3. 兜底 utf-8(requests 默认 ISO-8859-1 会导致中文乱码)
response.encoding = 'utf-8'
return response.text
# 特定域名的备用IP(当DNS解析的IP不通时使用)
ALTERNATIVE_IPS = {
'github.com': ['140.82.121.3', '140.82.114.4', '140.82.121.4'],
'www.github.com': ['140.82.121.3', '140.82.114.4', '140.82.121.4'],
}
class SiteAnalyzer:
"""网站分析器"""
def __init__(self, url, timeout=30):
self.url = self._normalize_url(url)
self.timeout = timeout
self.parsed_url = urlparse(self.url)
self.domain = self.parsed_url.netloc
self.results = {}
def _normalize_url(self, url):
"""标准化URL"""
if not url.startswith(('http://', 'https://')):
url = 'https://' + url
return url
def analyze(self):
"""执行完整分析"""
import time
start_time = time.time()
print(f"\n🔍 正在分析: {self.url}")
# 基础检测
self.results['url'] = self.url
self.results['domain'] = self.domain
self.results['timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 执行各项检测
self._check_accessibility()
self._check_ai_crawler_access() # AI爬虫导航文件检测(robots.txt/llms.txt/sitemap.xml)
self._check_ipv6()
self._check_ssl()
self._check_seo() # ← _raw_html 在这里设置
self._check_ip_intelligence() # IP归属地/备案合规(依赖_raw_html)
self._check_ai_discoverability(getattr(self, '_soup', None))
self._check_performance()
self._calculate_score()
# 记录总分析耗时
total_time = time.time() - start_time
self.results['analyze_time'] = round(total_time, 2)
# 更新域名耗时统计
self._update_domain_timing(total_time)
return self.results
def _check_accessibility(self):
"""检测网站可用性"""
# 先尝试默认连接
success = self._try_connect(self.url)
# 如果失败且有备用IP,逐个尝试
if not success and self.domain in ALTERNATIVE_IPS:
for ip in ALTERNATIVE_IPS[self.domain]:
alt_url = self.url.replace(self.domain, ip)
if self._try_connect(alt_url, host_header=self.domain):
self.results['resolved_ip'] = ip
break
def _check_ai_crawler_access(self):
"""检测AI爬虫导航文件:robots.txt、llms.txt、sitemap.xml 及各AI爬虫放行状态"""
import urllib.request
import urllib.error
base = 'https://' + self.domain
headers_req = {'User-Agent': 'Mozilla/5.0 (compatible; AI/1.0)'}
result = {
'robots_txt': {'exists': False, 'status': None, 'content': None, 'ai_bots': {}},
'llms_txt': {'exists': False, 'status': None},
'sitemap_xml': {'exists': False, 'status': None, 'url': None},
}
# ---- robots.txt ----
try:
req = urllib.request.Request(base + '/robots.txt', headers=headers_req)
with urllib.request.urlopen(req, timeout=10) as resp:
status = resp.status
content = resp.read().decode('utf-8', errors='ignore')
result['robots_txt']['exists'] = True
result['robots_txt']['status'] = status
result['robots_txt']['content'] = content
# 检测各AI爬虫 User-agent
bot_pattern = re.compile(r'^User-agent:\s*(.+)$', re.M | re.I)
allow_pattern = re.compile(r'^(Allow|Disallow):\s*(.+)$', re.M | re.I)
current_bot = None
bot_rules = {}
for line in content.splitlines():
line = line.strip()
if not line or line.startswith('#'):
continue
bm = bot_pattern.match(line)
if bm:
current_bot = bm.group(1).strip()
if current_bot not in bot_rules:
bot_rules[current_bot] = []
elif current_bot and allow_pattern.match(line):
bot_rules[current_bot].append(line)
result['robots_txt']['ai_bots'] = bot_rules
except urllib.error.HTTPError as e:
result['robots_txt']['status'] = e.code
except Exception:
pass
# ---- llms.txt ----
try:
req = urllib.request.Request(base + '/llms.txt', headers=headers_req)
with urllib.request.urlopen(req, timeout=10) as resp:
result['llms_txt']['exists'] = True
result['llms_txt']['status'] = resp.status
except urllib.error.HTTPError as e:
result['llms_txt']['status'] = e.code
except Exception:
pass
# ---- sitemap.xml ----
try:
# 尝试根目录
req = urllib.request.Request(base + '/sitemap.xml', headers=headers_req)
with urllib.request.urlopen(req, timeout=10) as resp:
result['sitemap_xml']['exists'] = True
result['sitemap_xml']['status'] = resp.status
result['sitemap_xml']['url'] = base + '/sitemap.xml'
except urllib.error.HTTPError:
# 尝试 sitemap-index.xml
try:
req = urllib.request.Request(base + '/sitemap-index.xml', headers=headers_req)
with urllib.request.urlopen(req, timeout=10) as resp:
result['sitemap_xml']['exists'] = True
result['sitemap_xml']['status'] = resp.status
result['sitemap_xml']['url'] = base + '/sitemap-index.xml'
except urllib.error.HTTPError as e:
result['sitemap_xml']['status'] = e.code
except Exception:
pass
except Exception:
pass
self.results['ai_crawler_access'] = result
def _try_connect(self, url, host_header=None):
"""尝试连接URL"""
try:
start_time = time.time()
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}
if host_header:
headers['Host'] = host_header
response = requests.get(
url,
timeout=self.timeout,
allow_redirects=True,
headers=headers,
verify=False # 使用IP时证书可能不匹配
)
response_time = time.time() - start_time
self.results['status_code'] = response.status_code
self.results['response_time'] = round(response_time, 3)
self.results['final_url'] = response.url
self.results['redirect_count'] = len(response.history)
self.results['content_length'] = len(response.content)
self.results['content_type'] = response.headers.get('Content-Type', '未知')
self.results['server'] = response.headers.get('Server', '未知')
# 检测 Cloudflare JS 挑战页(521 + JS redirect + __jsluid_s cookie)
# __jsluid_s 在 Set-Cookie 响应头中,不在 body 里
raw_text = response.text
has_cf_cookie = any('jsluid' in str(v) for v in response.headers.values())
is_cloudflare_challenge = (
response.status_code == 521
and 'location.href' in raw_text
and has_cf_cookie
)
if is_cloudflare_challenge:
# JS 挑战页说明目标返回了 SPA 入口(可能需要 hash 路由)
# 记录真实 final_url 用于 hash 路由探测
self.results['is_spa'] = True
self.results['spa_final_url'] = response.url
# 重定向链
if response.history:
self.results['redirect_chain'] = [r.url for r in response.history]
self.results['redirect_chain'].append(response.url)
self.results['accessible'] = True
return True
except requests.exceptions.Timeout:
if not host_header: # 只在默认连接时记录错误
self.results['accessible'] = False
self.results['error'] = '请求超时'
return False
except requests.exceptions.ConnectionError:
if not host_header:
self.results['accessible'] = False
self.results['error'] = '连接失败'
return False
except Exception as e:
if not host_header:
self.results['accessible'] = False
self.results['error'] = str(e)
return False
def _render_headless(self, url):
"""使用 chromium headless 渲染 SPA 页面,返回渲染后的 HTML 或 None"""
try:
cmd = [
'/usr/bin/chromium-browser',
'--headless=new',
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-gpu',
'--dump-dom',
f'--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
url
]
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0 and result.stdout:
return result.stdout
except subprocess.TimeoutExpired:
pass
except FileNotFoundError:
pass
except Exception:
pass
return None
def _check_ipv6(self):
"""检测IPv6支持(通过dig查询DNS AAAA记录,不依赖本机网络栈)"""
import subprocess
try:
# 查 IPv6 (AAAA) — 用 1.1.1.1 避免本机 stub-resolver 行为异常
r6 = subprocess.run(['dig', '@1.1.1.1', '+short', 'AAAA', self.domain],
capture_output=True, text=True, timeout=5)
ipv6_addresses = [line.strip() for line in r6.stdout.splitlines() if line.strip()]
# 查 IPv4 (A)
r4 = subprocess.run(['dig', '@1.1.1.1', '+short', 'A', self.domain],
capture_output=True, text=True, timeout=5)
ipv4_addresses = [line.strip() for line in r4.stdout.splitlines() if line.strip()]
self.results['ipv6'] = {
'supported': len(ipv6_addresses) > 0,
'ipv6_count': len(ipv6_addresses),
'ipv4_count': len(ipv4_addresses),
'ipv6_addresses': ipv6_addresses,
'ipv4_addresses': ipv4_addresses,
'all_ips': ipv6_addresses + ipv4_addresses
}
except Exception as e:
self.results['ipv6'] = {
'supported': False,
'error': str(e),
'ipv6_count': 0,
'ipv4_count': 0,
'ipv6_addresses': [],
'ipv4_addresses': [],
'all_ips': []
}
def _check_ip_intelligence(self):
"""查询IP归属地/运营商/ASN,判断备案合规性
判定逻辑:
- 国内IP(countryCode=CN):必须有ICP备案,有公网安备更佳
- 国外IP(countryCode!=CN):有ICP/公网安备声明 → 可疑警告
- IP数据来源:ip-api.com(免费,无需key,90请求/分钟)
"""
ip_intel = {
'provider': 'ip-api.com',
'query_method': None, # 'ipv4' / 'ipv6' / None
'ip': None,
'asn': None,
'isp': None,
'org': None,
'region': None,
'city': None,
'country': None,
'country_code': None,
'is_china': None, # bool,是否中国IP
'proxy_suspicion': None, # 'none' / 'low' / 'medium' / 'high'
'compliance': {
'is_domestic': None, # bool,是否国内IP
'has_icp': None, # bool,是否检测到ICP备案
'has_gongan': None, # bool,是否检测到公网安备
}
}
# 取主IP(优先 IPv4 用于查询)
all_ips = self.results.get('ipv6', {}).get('all_ips', [])
if not all_ips:
self.results['ip_intel'] = ip_intel
return
# 优先用 resolved_ip(_check_accessibility 中可能已设置),否则用第一个 IPv4
primary_ip = self.results.get('resolved_ip')
query_ip = None
query_method = None
if primary_ip:
query_ip = primary_ip
query_method = 'ipv6' if ':' in primary_ip else 'ipv4'
else:
ipv4s = self.results.get('ipv6', {}).get('ipv4_addresses', [])
if ipv4s:
query_ip = ipv4s[0]
query_method = 'ipv4'
elif all_ips:
query_ip = all_ips[0]
query_method = 'ipv6' if ':' in query_ip else 'ipv4'
ip_intel['query_method'] = query_method
ip_intel['ip'] = query_ip
if not query_ip:
self.results['ip_intel'] = ip_intel
return
# 查询 ip-api.com
# 使用 batch API 一次查询多个字段,减少请求次数
try:
fields = 'status,message,country,countryCode,region,regionName,city,isp,org,asn,query'
api_url = f'http://ip-api.com/json/{query_ip}?fields={fields}'
resp = requests.get(api_url, timeout=10)
data = resp.json()
except Exception as e:
ip_intel['error'] = str(e)
self.results['ip_intel'] = ip_intel
return
if data.get('status') == 'fail':
ip_intel['error'] = data.get('message', 'query failed')
# IPv6 查询失败,尝试回退到 IPv4
if query_method == 'ipv6' or (query_method is None and ':' in (query_ip or '')):
ipv4s = self.results.get('ipv6', {}).get('ipv4_addresses', [])
if ipv4s:
query_ip = ipv4s[0]
query_method = 'ipv4'
ip_intel['query_method'] = 'ipv4'
ip_intel['ip'] = query_ip
try:
resp2 = requests.get(f'http://ip-api.com/json/{query_ip}?fields={fields}', timeout=10)
data = resp2.json()
if data.get('status') == 'success':
# 用 IPv4 结果继续
pass
else:
ip_intel['error'] = data.get('message', 'query failed')
self.results['ip_intel'] = ip_intel
return
except Exception as e2:
ip_intel['error'] = str(e2)
self.results['ip_intel'] = ip_intel
return
else:
self.results['ip_intel'] = ip_intel
return
# 填充基本信息
ip_intel['country'] = data.get('country', '')
ip_intel['country_code'] = data.get('countryCode', '')
ip_intel['region'] = data.get('regionName', '')
ip_intel['city'] = data.get('city', '')
ip_intel['isp'] = data.get('isp', '')
ip_intel['org'] = data.get('org', '')
ip_intel['asn'] = data.get('asn', '')
ip_intel['is_china'] = ip_intel['country_code'] == 'CN'
# ASN 推断网络类型
asn_str = (ip_intel['asn'] or '').lower()
isp_str = (ip_intel['isp'] or '').lower()
org_str = (ip_intel['org'] or '').lower()
# ========== 备案合规判定 ==========
comp = ip_intel['compliance']
comp['is_domestic'] = ip_intel['is_china']
# 获取当前站点的ICP/公安备案状态(由 _check_seo 或 _check_ai_discoverability 设置)
icp_found = self._get_icp_status()
gongan_found = self._get_gongan_status()
comp['has_icp'] = icp_found
# 已知热门站点兜底的公网安备号也算入
if not gongan_found and ip_intel.get('gongan_number'):
gongan_found = True
comp['has_gongan'] = gongan_found
# 公网安备正则(格式:省份简称 + 公安 + 网安备/公网安备 + 数字,如"京公网安备 11010802020088号")
gongan_regex = re.compile(
r'(京|沪|粤|浙|苏|鲁|豫|川|渝|鄂|湘|皖|闽|赣|桂|黔|滇|冀|晋|辽|吉|黑|蒙|陕|甘|青|藏|新|琼|宁)公网安备 ?\d+号?',
re.IGNORECASE
)
# 再次扫描页面文本(可见文本 > 源码),单独检测公网安备(icp_filing不包含公安)
page_text = getattr(self, '_raw_html', '')[:200000] if hasattr(self, '_raw_html') else ''
gongan_match = gongan_regex.search(page_text)
if gongan_match:
comp['has_gongan'] = True
ip_intel['gongan_number'] = gongan_match.group()
self.results['ip_intel'] = ip_intel
def _get_icp_status(self):
"""从已完成的检测结果中获取ICP备案状态"""
# 优先级:seo.ai_discoverability > seo.ai_trust > 直接搜索 > 已知热门站点兜底
ai_disc = self.results.get('seo', {}).get('ai_discoverability', {})
auth_items = ai_disc.get('authority', {}).get('items', [])
for item in auth_items:
if 'ICP' in item.get('text', '') or '备案' in item.get('text', ''):
if item.get('icon') in ('✅', '🟡'):
return True
# 直接从 raw_html 扫描(兜底)
page = getattr(self, '_raw_html', '')[:200000] if hasattr(self, '_raw_html') else ''
icp_regex = re.compile(r'(京|沪|粤|浙|苏|鲁|豫|川|渝|鄂|湘|皖|闽|赣|桂|黔|滇|冀|晋|辽|吉|黑|蒙|陕|甘|青|藏|新|琼|宁)ICP[证备]?\d+号?', re.IGNORECASE)
if page and icp_regex.search(page):
return True
# 已知热门站点兜底(SPA站点或强制跳转页面无法抓取内容时使用)
# 格式:domain → {"icp": bool, "gongan": str or None, "est_time": 秒}
known_domains = {
'baidu.com': {"icp": True, "gongan": "京公网安备11000002000001号", "est_time": 3},
'bilibili.com': {"icp": True, "gongan": "沪公网安备31011002002436号", "est_time": 15},
'douyin.com': {"icp": True, "gongan": None, "est_time": 12},
'toutiao.com': {"icp": True, "gongan": None, "est_time": 10},
'zhihu.com': {"icp": True, "gongan": "京公网安备11010802020088号", "est_time": 8},
'weibo.com': {"icp": True, "gongan": None, "est_time": 10},
'jd.com': {"icp": True, "gongan": None, "est_time": 8},
'taobao.com': {"icp": True, "gongan": None, "est_time": 12},
'tmall.com': {"icp": True, "gongan": None, "est_time": 10},
'alipay.com': {"icp": True, "gongan": None, "est_time": 6},
'163.com': {"icp": True, "gongan": None, "est_time": 5},
'qq.com': {"icp": True, "gongan": None, "est_time": 8},
'weixin.qq.com': {"icp": True, "gongan": None, "est_time": 10},
'xiaohongshu.com': {"icp": True, "gongan": None, "est_time": 12},
'kuaishou.com': {"icp": True, "gongan": None, "est_time": 12},
'pinduoduo.com': {"icp": True, "gongan": None, "est_time": 8},
'meituan.com': {"icp": True, "gongan": None, "est_time": 6},
'douban.com': {"icp": True, "gongan": None, "est_time": 5},
'juejin.cn': {"icp": True, "gongan": None, "est_time": 5},
'miit.gov.cn': {"icp": True, "gongan": None, "est_time": 8},
'beian.miit.gov.cn': {"icp": True, "gongan": None, "est_time": 8},
}
# 从 timing_stats.json 读取实际平均耗时,替换 est_time
import json
import os
timing_file = os.path.join(os.path.dirname(__file__), 'timing_stats.json')
if os.path.exists(timing_file):
try:
with open(timing_file, 'r') as f:
timing_stats = json.load(f)
for d in known_domains:
if d in timing_stats:
known_domains[d]['est_time'] = timing_stats[d].get('avg', known_domains[d]['est_time'])
except:
pass
for d, info in known_domains.items():
if d in self.domain:
if info["icp"]:
if info["gongan"]:
self.results.setdefault('ip_intel', {})
self.results['ip_intel']['gongan_number'] = info["gongan"]
return True
return False
def _get_gongan_status(self):
"""检测公网安备状态"""
page = getattr(self, '_raw_html', '')[:200000] if hasattr(self, '_raw_html') else ''
if page:
gongan_regex = re.compile(r'(京|沪|粤|浙|苏|鲁|豫|川|渝|鄂|湘|皖|闽|赣|桂|黔|滇|冀|晋|辽|吉|黑|蒙|陕|甘|青|藏|新|琼|宁)公网安备 *\d+号?', re.IGNORECASE)
if gongan_regex.search(page):
return True
# 页面为空时,查已知热门站点兜底记录
if self.results.get('ip_intel', {}).get('gongan_number'):
return True
return False
def _check_ssl(self):
"""检测SSL证书"""
if not self.url.startswith('https://'):
self.results['ssl'] = {'valid': False, 'reason': '未使用HTTPS'}
return
try:
context = ssl.create_default_context()
# 使用解析的IP(如果有)或域名
connect_host = self.results.get('resolved_ip', self.domain)
with socket.create_connection((connect_host, 443), timeout=self.timeout) as sock:
with context.wrap_socket(sock, server_hostname=self.domain) as ssock:
cert = ssock.getpeercert()
# 解析证书信息
not_after = datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')
not_before = datetime.strptime(cert['notBefore'], '%b %d %H:%M:%S %Y %Z')
days_remaining = (not_after - datetime.now()).days
# 提取组织信息
subject = dict(x[0] for x in cert.get('subject', []))
issuer = dict(x[0] for x in cert.get('issuer', []))
self.results['ssl'] = {
'valid': True,
'issuer': issuer.get('organizationName', '未知'),
'subject': subject.get('commonName', '未知'),
'not_before': not_before.strftime('%Y-%m-%d'),
'not_after': not_after.strftime('%Y-%m-%d'),
'days_remaining': days_remaining,
'serial_number': cert.get('serialNumber', '未知'),
'version': cert.get('version', '未知'),
}
# 证书状态判断
if days_remaining < 0:
self.results['ssl']['status'] = '已过期'
self.results['ssl']['valid'] = False
elif days_remaining < 30:
self.results['ssl']['status'] = '即将过期'
else:
self.results['ssl']['status'] = '有效'
except ssl.SSLCertVerificationError as e:
self.results['ssl'] = {'valid': False, 'reason': f'证书验证失败: {str(e)}'}
except Exception as e:
self.results['ssl'] = {'valid': False, 'reason': f'检测失败: {str(e)}'}
def _check_seo(self):
"""检测SEO信息"""
try:
# 使用解析的IP(如果有)或URL
request_url = self.url
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}
if 'resolved_ip' in self.results:
request_url = self.url.replace(self.domain, self.results['resolved_ip'])
headers['Host'] = self.domain
response = requests.get(
request_url,
timeout=self.timeout,
headers=headers,
verify=False
)
html_text = fix_encoding(response)
# 检测 Cloudflare JS 挑战页(521 + JS redirect + __jsluid)
# 尝试抓取 SPA hash 路由页面
is_cloudflare = (
response.status_code == 521
and 'location.href' in html_text
and ('__jsluid' in html_text or '__jsl_clearance' in html_text)
)
if is_cloudflare:
# 尝试常见的 hash 路由路径
hash_paths = [
'/#/Integrated/index',
'/#/recordcheck/index',
'/#/service/index',
'/#/',
]
for hash_path in hash_paths:
try:
hash_url = request_url.rstrip('/') + hash_path
hresp = requests.get(
hash_url,
timeout=self.timeout,
headers=headers,
verify=False
)
if hresp.status_code == 200 and len(hresp.text) > 500:
html_text = fix_encoding(hresp)
self.results['spa_final_url'] = hash_url
break
except:
pass
# 检测普通 Vue SPA(返回 200 但内容是 JS 渲染的)
# 特征:HTML 中有 chunk-vendors、id="app"、Vue app 初始化
if not self.results.get('is_spa'):
spa_indicators = ['chunk-vendors', 'id="app"', '__VUE_DEVTOOLS_PLUGIN__', '__VUE_OPTIONS_API__']
if sum(1 for ind in spa_indicators if ind in html_text) >= 2:
self.results['is_spa'] = True
# URL 中有 hash 路由也视为 SPA
if '/#/' in self.url:
self.results['is_spa'] = True
# 如果是 SPA(Cloudflare 521 或 hash 路由)但页面内容仍是挑战页或为空
is_cf_521 = self.results.get('status_code') == 521
# SPA + (Cloudflare 521 或 内容太短 或 普通Vue SPA) → headless 渲染
if self.results.get('is_spa') and (is_cf_521 or len(html_text) < 500 or
(self.results.get('status_code') == 200 and 'chunk-vendors' in html_text)):
rendered_html = self._render_headless(self.url)
if rendered_html:
html_text = rendered_html
self.results['headless_rendered'] = True
soup = BeautifulSoup(html_text, 'html.parser')
self._soup = soup # 保存供AI可发现性检测使用
self._raw_html = html_text # 保存原始HTML供ICP等检测
seo = {}
# 标题
title_tag = soup.find('title')
seo['title'] = title_tag.string.strip() if title_tag and title_tag.string else '未设置'
seo['title_length'] = len(seo['title']) if seo['title'] != '未设置' else 0
# Meta描述
meta_desc = soup.find('meta', attrs={'name': 'description'})
seo['description'] = meta_desc['content'].strip() if meta_desc and meta_desc.get('content') else '未设置'
seo['description_length'] = len(seo['description']) if seo['description'] != '未设置' else 0
# Meta关键词
meta_keywords = soup.find('meta', attrs={'name': 'keywords'})
seo['keywords'] = meta_keywords['content'].strip() if meta_keywords and meta_keywords.get('content') else '未设置'
# H标签统计
for i in range(1, 7):
h_tags = soup.find_all(f'h{i}')
seo[f'h{i}_count'] = len(h_tags)
if h_tags:
seo[f'h{i}_texts'] = [h.get_text().strip()[:50] for h in h_tags[:5]]
# 图片统计
images = soup.find_all('img')
seo['total_images'] = len(images)
seo['images_without_alt'] = len([img for img in images if not img.get('alt')])
seo['images_alt_ratio'] = round(
(1 - seo['images_without_alt'] / max(seo['total_images'], 1)) * 100, 1
)
# 链接统计
links = soup.find_all('a', href=True)
seo['total_links'] = len(links)
seo['internal_links'] = len([l for l in links if self.domain in l.get('href', '')])
seo['external_links'] = seo['total_links'] - seo['internal_links']
# Canonical标签
canonical = soup.find('link', attrs={'rel': 'canonical'})
seo['canonical'] = canonical['href'] if canonical and canonical.get('href') else '未设置'
# Robots meta
robots = soup.find('meta', attrs={'name': 'robots'})
seo['robots'] = robots['content'] if robots and robots.get('content') else '未设置'
# Viewport
viewport = soup.find('meta', attrs={'name': 'viewport'})
seo['viewport'] = viewport['content'] if viewport and viewport.get('content') else '未设置'
# 移动端适配检测(增强版)
mobile_friendly = False
mobile_type = []
# 1. 检查 viewport 标签(响应式设计)
if 'width=device' in seo.get('viewport', '').lower():
mobile_friendly = True
mobile_type.append('响应式设计')
# 2. 检查是否有移动端子域名链接
mobile_links = soup.find_all('a', href=True)
for link in mobile_links:
href = link.get('href', '')
if any(m in href for m in ['m.' + self.domain, 'mobile.' + self.domain]):
mobile_friendly = True
mobile_type.append('移动端子域名')
break
# 3. 检查页面内是否有移动端跳转JS代码
scripts = soup.find_all('script')
for script in scripts:
if script.string:
script_text = script.string.lower()
if any(keyword in script_text for keyword in ['useragent', 'mobile', 'm.baidu', 'm.']):
if 'location' in script_text or 'redirect' in script_text or 'href' in script_text:
mobile_friendly = True
mobile_type.append('JS跳转适配')
break
# 4. 如果桌面版没检测到,用手机UA再访问一次(百度等网站会根据UA返回不同内容)
if not mobile_friendly:
try:
mobile_ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1'
mobile_response = requests.get(self.url, timeout=self.timeout, headers={'User-Agent': mobile_ua})
mobile_soup = BeautifulSoup(fix_encoding(mobile_response), 'html.parser')
# 检查手机UA返回的页面是否有viewport
mobile_viewport = mobile_soup.find('meta', attrs={'name': 'viewport'})
if mobile_viewport and mobile_viewport.get('content'):
if 'width=device' in mobile_viewport['content'].lower():
mobile_friendly = True
mobile_type.append('UA自适应')
# 检查是否重定向到了移动子域名
if mobile_response.url and any(m in mobile_response.url for m in ['m.', 'mobile.']):
if 'UA重定向' not in mobile_type:
mobile_friendly = True
mobile_type.append('UA重定向')
except:
pass
seo['mobile_friendly'] = mobile_friendly
seo['mobile_type'] = mobile_type if mobile_type else ['无']
# ==================== AI信任度指标检测 ====================
ai_trust = {}
# 1. JSON-LD 结构化数据(最重要!)
json_ld_scripts = soup.find_all('script', attrs={'type': 'application/ld+json'})
json_ld_types = []
for script in json_ld_scripts:
try:
import json
data = json.loads(script.string)
if isinstance(data, dict):
json_ld_types.append(data.get('@type', 'Unknown'))
elif isinstance(data, list):
for item in data:
if isinstance(item, dict):
json_ld_types.append(item.get('@type', 'Unknown'))
except:
pass
ai_trust['json_ld'] = {
'exists': len(json_ld_scripts) > 0,
'count': len(json_ld_scripts),
'types': json_ld_types,
'importance': '高 - AI搜索引擎优先解析结构化数据,直接用于生成摘要和知识图谱'
}
# 2. Open Graph 标签完整性
og_tags = {}
for og in soup.find_all('meta', attrs={'property': lambda x: x and x.startswith('og:')}):
og_tags[og['property']] = og.get('content', '')
og_essential = ['og:title', 'og:description', 'og:image', 'og:url']
og_missing = [tag for tag in og_essential if tag not in og_tags]
ai_trust['open_graph'] = {
'exists': len(og_tags) > 0,
'count': len(og_tags),
'missing': og_missing,
'complete': len(og_missing) == 0,
'importance': '高 - 社交媒体和AI引用时会优先使用OG标签的内容'
}
seo['open_graph'] = og_tags
# 3. Twitter Card 标签
twitter_tags = {}
for meta in soup.find_all('meta', attrs={'name': lambda x: x and x.startswith('twitter:')}):
twitter_tags[meta['name']] = meta.get('content', '')
for meta in soup.find_all('meta', attrs={'property': lambda x: x and x.startswith('twitter:')}):
twitter_tags[meta['property']] = meta.get('content', '')
ai_trust['twitter_card'] = {
'exists': len(twitter_tags) > 0,
'count': len(twitter_tags),
'importance': '中 - Twitter/X平台和部分AI会参考Twitter Card数据'
}
# 4. Canonical 标签
canonical = soup.find('link', attrs={'rel': 'canonical'})
seo['canonical'] = canonical['href'] if canonical and canonical.get('href') else '未设置'
ai_trust['canonical'] = {
'exists': canonical is not None,
'value': seo['canonical'],
'importance': '高 - 告诉AI这是权威版本,避免重复内容稀释权重'
}
# 5. Author 和 Publisher 标签
author_meta = soup.find('meta', attrs={'name': 'author'})
publisher_meta = soup.find('meta', attrs={'name': 'publisher'})
author_link = soup.find('link', attrs={'rel': 'author'})
ai_trust['authorship'] = {
'has_author': author_meta is not None or author_link is not None,
'has_publisher': publisher_meta is not None,
'author': author_meta.get('content', '') if author_meta else '',
'importance': '中高 - 明确的内容创作者信息增加可信度,AI更倾向引用有明确来源的内容'
}
# 6. 发布/修改日期
date_published = soup.find('meta', attrs={'property': 'article:published_time'})
date_modified = soup.find('meta', attrs={'property': 'article:modified_time'})
time_tag = soup.find('time')
ai_trust['dates'] = {
'has_published': date_published is not None,
'has_modified': date_modified is not None,
'has_time_tag': time_tag is not None,
'published': date_published.get('content', '') if date_published else '',
'importance': '高 - AI优先引用有明确时间的内容,过时内容会被降权'
}
# 7. Favicon 网站图标
favicon = soup.find('link', attrs={'rel': lambda x: x and 'icon' in x.lower()})
apple_icon = soup.find('link', attrs={'rel': 'apple-touch-icon'})
ai_trust['favicon'] = {
'has_favicon': favicon is not None,
'has_apple_icon': apple_icon is not None,
'importance': '低 - 提升品牌识别度,AI在展示搜索结果时会显示图标'
}
# 8. 语义化HTML标签
semantic_tags = ['article', 'section', 'nav', 'aside', 'header', 'footer', 'main']
found_semantic = [tag for tag in semantic_tags if soup.find(tag)]
ai_trust['semantic_html'] = {
'tags_found': found_semantic,
'count': len(found_semantic),
'importance': '高 - 语义化标签帮助AI理解页面结构和内容层次'
}
# 9. H标签层级结构
h_tags = {}
for i in range(1, 7):
h_tags[f'h{i}'] = len(soup.find_all(f'h{i}'))
has_h1 = h_tags.get('h1', 0) > 0
h_hierarchy_ok = has_h1 and (h_tags.get('h2', 0) > 0 or h_tags.get('h3', 0) > 0)
ai_trust['heading_structure'] = {
'hierarchy': h_tags,
'has_h1': has_h1,
'proper_hierarchy': h_hierarchy_ok,
'importance': '高 - 清晰的标题层级帮助AI理解内容主题和重点'
}
# 10. alt属性完整性
images = soup.find_all('img')
imgs_with_alt = [img for img in images if img.get('alt') and img.get('alt').strip()]
seo['total_images'] = len(images)
seo['images_without_alt'] = len(images) - len(imgs_with_alt)
ai_trust['image_alt'] = {
'total_images': len(images),
'with_alt': len(imgs_with_alt),
'completeness': f"{len(imgs_with_alt)}/{len(images)}" if images else 'N/A',
'importance': '高 - alt文本是AI理解图片内容的唯一依据,影响图片搜索排名'
}
# 11. 页面语言声明
html_tag = soup.find('html')
lang = html_tag.get('lang', '') if html_tag else ''
ai_trust['language'] = {
'declared': bool(lang),
'value': lang,
'importance': '中 - 明确的语言声明帮助AI正确处理多语言内容'
}
# 计算AI信任度得分
trust_score = 0
trust_max = 100
if ai_trust['json_ld']['exists']: trust_score += 20
if ai_trust['open_graph']['complete']: trust_score += 15
if ai_trust['canonical']['exists']: trust_score += 10
if ai_trust['authorship']['has_author']: trust_score += 10
if ai_trust['dates']['has_published']: trust_score += 10
if ai_trust['semantic_html']['count'] >= 3: trust_score += 15
if ai_trust['heading_structure']['proper_hierarchy']: trust_score += 10
if ai_trust['image_alt']['total_images'] == 0 or (ai_trust['image_alt']['with_alt'] / max(ai_trust['image_alt']['total_images'], 1) > 0.8): trust_score += 5
if ai_trust['language']['declared']: trust_score += 5
ai_trust['score'] = trust_score
ai_trust['max_score'] = trust_max
seo['ai_trust'] = ai_trust
self.results['seo'] = seo
except Exception as e:
self.results['seo'] = {'error': str(e)}
def _check_ai_discoverability(self, soup):
"""检测AI可发现性(面向国内平台)
评分体系:
- 结构化数据 (20分)
- 内容可引用性 (25分)
- 自媒体适配性 (20分)
- 权威性信号 (20分)
- 可访问性 (15分)
"""
discover = {}
score = 0
details = []
# ==================== 1. 结构化数据 (20分) ====================
struct_score = 0
# JSON-LD (8分)
json_ld = self.results.get('seo', {}).get('ai_trust', {}).get('json_ld', {})
if json_ld.get('exists'):
struct_score += 8
details.append({'icon': '✅', 'text': 'JSON-LD结构化数据', 'score': 8})
else:
details.append({'icon': '❌', 'text': '缺少JSON-LD', 'score': 0, 'tip': '添加JSON-LD帮助AI理解内容'})
# Open Graph (12分) - 微信/头条/知乎通用
og = self.results.get('seo', {}).get('open_graph', {})
og_score = 0
if og.get('og:title'): og_score += 3
if og.get('og:description'): og_score += 3
if og.get('og:image'): og_score += 3
if og.get('og:url'): og_score += 3
struct_score += og_score
if og_score == 12:
details.append({'icon': '✅', 'text': 'Open Graph完整', 'score': 12})
elif og_score > 0:
details.append({'icon': '⚠️', 'text': f'Open Graph部分缺失', 'score': og_score, 'tip': '补全og:title/description/image/url'})
else:
details.append({'icon': '❌', 'text': '缺少Open Graph', 'score': 0, 'tip': '微信/头条/知乎分享都需要OG标签'})
# AI爬虫导航文件 (10分)
# robots.txt (3分) + llms.txt (3分) + sitemap.xml (2分) + AI爬虫显式放行 (2分)
ai_nav_score = 0
ai_nav_details = []
ai_nav = self.results.get('ai_crawler_access', {})
robots = ai_nav.get('robots_txt', {})
llms = ai_nav.get('llms_txt', {})
sitemap = ai_nav.get('sitemap_xml', {})
if robots.get('exists'):
ai_nav_score += 3
ai_nav_details.append({'icon': '✅', 'text': 'robots.txt存在', 'score': 3})
else:
ai_nav_details.append({'icon': '❌', 'text': 'robots.txt缺失', 'score': 0, 'tip': '添加robots.txt显式声明允许AI爬虫抓取'})
if llms.get('exists'):
ai_nav_score += 3
ai_nav_details.append({'icon': '✅', 'text': 'llms.txt存在(AI导航文件)', 'score': 3})
else:
ai_nav_details.append({'icon': '❌', 'text': 'llms.txt缺失', 'score': 0, 'tip': '添加llms.txt为AI爬虫提供站点导航'})
if sitemap.get('exists'):
ai_nav_score += 2
ai_nav_details.append({'icon': '✅', 'text': 'sitemap.xml存在', 'score': 2})
else:
ai_nav_details.append({'icon': '❌', 'text': 'sitemap.xml缺失', 'score': 0, 'tip': '添加sitemap.xml加速搜索引擎收录'})
# AI爬虫显式放行(GPTBot/ClaudeBot/PerplexityBot/GeminiBot)
if robots.get('exists'):
bot_rules = robots.get('ai_bots', {})
major_bots = ['GPTBot', 'ClaudeBot', 'PerplexityBot', 'GeminiBot', 'GoogleExtended', 'Diffbot']
allowed = [b for b in major_bots if b in bot_rules]
if allowed:
ai_nav_score += 2
ai_nav_details.append({'icon': '✅', 'text': f'AI爬虫显式放行: {", ".join(allowed)}', 'score': 2})
else:
# 通配符 * Allow / 或完全没声明 = 默认允许(不算错,但没加分)
if '*' in bot_rules or (len(bot_rules) == 0 and robots.get('exists')):
ai_nav_details.append({'icon': 'ℹ️', 'text': 'robots.txt无显式AI爬虫规则(默认允许)', 'score': 0})
else: