-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfastapi_server.py
More file actions
2563 lines (2181 loc) · 104 KB
/
Copy pathfastapi_server.py
File metadata and controls
2563 lines (2181 loc) · 104 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
from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import logging
import time
from datetime import datetime
import json
import os
from typing import Optional, Dict, Any, List, Tuple, AsyncGenerator
from urllib.parse import urljoin, quote
from bs4 import BeautifulSoup
from lxml import etree
import cloudscraper
import asyncio
from playwright.async_api import async_playwright
import re
from asyncio import Semaphore, PriorityQueue
from dataclasses import dataclass, field
from typing import Any
import aiojobs
from contextlib import asynccontextmanager
from threading import Lock
from lxml import html
from utils.turnstile_solver import TurnstileSolver
from utils.content_extractor import ContentExtractor
from utils.db_manager import DBManager
from models.manga import MangaInfo, Chapter, Image, Author, Genre, Type, ChapterInfo
from config.settings import (
DATA_DIR, API_HOST, API_PORT, LOG_CONFIG,
MONGO_COLLECTION_MANGA, MONGO_COLLECTION_CHAPTERS, MONGO_COLLECTION_IMAGES
)
from utils.browser_manager import BrowserManager
from utils.cache_manager import CacheManager
# 设置日志
logging.basicConfig(
level=logging.DEBUG, # 将日志级别设置为DEBUG
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler(LOG_CONFIG['filename'], encoding='utf-8')
]
)
logger = logging.getLogger(__name__)
# 设置其他模块的日志级别
logging.getLogger('urllib3').setLevel(logging.INFO)
logging.getLogger('playwright').setLevel(logging.DEBUG) # 设置playwright的日志级别为DEBUG
logging.getLogger('cloudscraper').setLevel(logging.DEBUG) # 设置cloudscraper的日志级别为DEBUG
# 添加默认请求头
DEFAULT_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1'
}
# 初始化数据库管理器
db_manager = DBManager()
@asynccontextmanager
async def lifespan(app: FastAPI):
# 启动时的操作
global scheduler
scheduler = await aiojobs.create_scheduler(limit=100)
await scheduler.spawn(process_request_queue())
# 连接数据库
await db_manager.connect()
yield
# 关闭时的操作
if scheduler:
await scheduler.close()
# 关闭数据库连接
await db_manager.close()
app = FastAPI(
title="漫画API",
description="提供漫画相关的API服务",
lifespan=lifespan
)
# 启用CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 初始化工具类
browser_manager = BrowserManager()
cache = CacheManager(ttl=86400) # 默认缓存时间改为24小时
# 定义请求优先级
class Priority:
HIGH = 1 # 用户直接请求
MEDIUM = 2 # 预加载请求
LOW = 3 # 缓存预热请求
@dataclass(order=True)
class PrioritizedRequest:
priority: int
timestamp: float
request: Any = field(compare=False)
# 初始化请求队列和调度器
request_queue = PriorityQueue()
scheduler = None
# 动态并发控制
MAX_CONCURRENT_REQUESTS = 10
MIN_CONCURRENT_REQUESTS = 3
current_concurrent_requests = 5
request_semaphore = Semaphore(current_concurrent_requests)
# 性能监控
request_metrics = {
'total_requests': 0,
'successful_requests': 0,
'failed_requests': 0,
'average_response_time': 0
}
async def process_request_queue():
while True:
try:
# 获取优先级最高的请求
prioritized_request = await request_queue.get()
request = prioritized_request.request
# 动态调整并发数
global current_concurrent_requests
if request_metrics['average_response_time'] > 2.0: # 如果平均响应时间超过2秒
current_concurrent_requests = max(MIN_CONCURRENT_REQUESTS, current_concurrent_requests - 1)
elif request_metrics['average_response_time'] < 1.0: # 如果平均响应时间小于1秒
current_concurrent_requests = min(MAX_CONCURRENT_REQUESTS, current_concurrent_requests + 1)
# 处理请求
async with request_semaphore:
start_time = time.time()
try:
await request['handler'](**request['params'])
request_metrics['successful_requests'] += 1
except Exception as e:
request_metrics['failed_requests'] += 1
logger.error(f"处理请求时出错: {str(e)}")
finally:
request_metrics['total_requests'] += 1
response_time = time.time() - start_time
request_metrics['average_response_time'] = (
request_metrics['average_response_time'] * (request_metrics['total_requests'] - 1) +
response_time
) / request_metrics['total_requests']
except Exception as e:
logger.error(f"队列处理器出错: {str(e)}")
await asyncio.sleep(1)
# 添加预热缓存的函数
async def warm_up_cache():
"""预热缓存"""
try:
# 预热首页数据
home_data = await get_page_content_with_playwright()
if home_data:
cache.set('home_page', home_data)
# 从首页数据中获取热门漫画进行预热
if home_data and 'hot_updates' in home_data:
for manga in home_data['hot_updates'][:5]: # 只预热前5个热门漫画
if 'link' in manga:
manga_path = manga['link'].replace('https://g-mh.org/manga/', '')
manga_info, chapters = await get_manga_info_with_playwright(f"https://g-mh.org/manga/{manga_path}")
if manga_info or chapters:
cache.set(f'chapters_{manga_path}', {
'manga_info': manga_info,
'chapters': chapters
})
except Exception as e:
logger.error(f"预热缓存时出错: {str(e)}")
async def get_search_results_with_cloudscraper(search_url: str, page: int = 1) -> Tuple[List[dict], dict]:
try:
scraper = cloudscraper.create_scraper(
browser={
'browser': 'chrome',
'platform': 'darwin',
'desktop': True,
'custom': 'Chrome/131.0.0.0'
}
)
logger.info("使用 Cloudscraper 访问搜索页面...")
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(
None,
lambda: scraper.get(
search_url,
allow_redirects=True,
timeout=30
)
)
if response.status_code == 200:
if '<html' not in response.text.lower():
logger.warning("响应内容可能不是有效的HTML")
return [], {'current_page': page, 'page_links': []}
tree = etree.HTML(str(BeautifulSoup(response.content, 'html.parser')))
# 提取漫画列表
manga_list = []
manga_items = tree.xpath('//div[contains(@class, "cardlist")]/div[contains(@class, "pb-2")]')
logger.info(f"找到 {len(manga_items)} 个漫画")
for item in manga_items:
try:
manga_info = {}
# 提取标题和链接
link_elem = item.xpath('.//a/@href')
title_elem = item.xpath('.//h3[contains(@class, "cardtitle")]/text()')
if link_elem and title_elem:
manga_info['title'] = title_elem[0].strip()
manga_info['link'] = link_elem[0]
if manga_info['link'] and not manga_info['link'].startswith('http'):
manga_info['link'] = urljoin(search_url, manga_info['link'])
# 提取封面图片
img_elem = item.xpath('.//img/@src')
if img_elem:
manga_info['cover'] = img_elem[0]
if not manga_info['cover'].startswith('http'):
manga_info['cover'] = urljoin(search_url, manga_info['cover'])
if manga_info.get('title') and manga_info.get('link'):
manga_list.append(manga_info)
except Exception as e:
logger.error(f"处理漫画信息时出错: {str(e)}")
continue
# 提取分页信息
pagination = {'current_page': page, 'page_links': []}
page_links = tree.xpath('//div[contains(@class, "flex justify-between items-center")]//a')
if page_links:
pagination['page_links'] = []
for link in page_links:
href = link.get('href')
text = ''.join(link.xpath('.//text()')).strip()
if href and text:
if not href.startswith('http'):
href = urljoin(search_url, href)
pagination['page_links'].append({
'text': text,
'link': href
})
return manga_list, pagination
else:
logger.warning(f"搜索请求失败,状态码: {response.status_code}")
return [], {'current_page': page, 'page_links': []}
except Exception as e:
logger.error(f"使用 Cloudscraper 搜索时出错: {str(e)}")
return [], {'current_page': page, 'page_links': []}
async def get_search_results_with_playwright(search_url: str, page: int = 1) -> Tuple[List[dict], dict]:
try:
browser_page = await browser_manager.get_page()
try:
logger.info("使用 Playwright 访问搜索页面...")
await browser_page.goto(search_url, timeout=30000)
await browser_page.wait_for_load_state('networkidle')
await browser_page.wait_for_timeout(3000)
content = await browser_page.content()
if not content:
logger.error("无法获取页面内容")
return [], {'current_page': page, 'page_links': []}
tree = etree.HTML(content)
# 提取漫画列表
manga_list = []
manga_items = tree.xpath('//div[contains(@class, "cardlist")]/div[contains(@class, "pb-2")]')
logger.info(f"找到 {len(manga_items)} 个漫画")
for item in manga_items:
try:
manga_info = {}
# 提取标题和链接
link_elem = item.xpath('.//a/@href')
title_elem = item.xpath('.//h3[contains(@class, "cardtitle")]/text()')
if link_elem and title_elem:
manga_info['title'] = title_elem[0].strip()
manga_info['link'] = link_elem[0]
if manga_info['link'] and not manga_info['link'].startswith('http'):
manga_info['link'] = urljoin(search_url, manga_info['link'])
# 提取封面图片
img_elem = item.xpath('.//img/@src')
if img_elem:
manga_info['cover'] = img_elem[0]
if not manga_info['cover'].startswith('http'):
manga_info['cover'] = urljoin(search_url, manga_info['cover'])
if manga_info.get('title') and manga_info.get('link'):
manga_list.append(manga_info)
except Exception as e:
logger.error(f"处理漫画信息时出错: {str(e)}")
continue
# 提取分页信息
pagination = {'current_page': page, 'page_links': []}
page_links = tree.xpath('//div[contains(@class, "flex justify-between items-center")]//a')
if page_links:
pagination['page_links'] = []
for link in page_links:
href = link.get('href')
text = ''.join(link.xpath('.//text()')).strip()
if href and text:
if not href.startswith('http'):
href = urljoin(search_url, href)
pagination['page_links'].append({
'text': text,
'link': href
})
return manga_list, pagination
finally:
await browser_manager.close()
except Exception as e:
logger.error(f"使用 Playwright 搜索时出错: {str(e)}")
return [], {'current_page': page, 'page_links': []}
@app.get("/api/manga/url")
async def get_manga_by_url(url: str):
"""
通过指定URL获取漫画列表
"""
try:
if not url:
raise HTTPException(status_code=400, detail="URL参数不能为空")
logger.info(f"接收到请求: /api/manga/url, URL: {url}")
# 尝试从缓存获取
cache_key = f'manga_url_{url}'
cached_data = cache.get(cache_key)
if cached_data:
return {
'code': 200,
'message': 'success',
'data': cached_data,
'timestamp': int(datetime.now().timestamp())
}
# 首先尝试使用 cloudscraper
manga_list, pagination = await get_search_results_with_cloudscraper(url, 1)
# 如果 cloudscraper 失败,尝试使用 playwright
if not manga_list:
logger.info("Cloudscraper失败,尝试使用Playwright")
manga_list, pagination = await get_search_results_with_playwright(url, 1)
if not manga_list:
logger.warning("未找到漫画列表")
return {
'code': 200,
'message': '未找到漫画列表',
'data': {
'manga_list': [],
'pagination': {'current_page': 1, 'page_links': []}
},
'timestamp': int(datetime.now().timestamp())
}
result_data = {
'manga_list': manga_list,
'pagination': pagination
}
# 缓存结果
cache.set(cache_key, result_data)
logger.info("成功获取漫画列表")
return {
'code': 200,
'message': 'success',
'data': result_data,
'timestamp': int(datetime.now().timestamp())
}
except Exception as e:
logger.error(f"获取漫画列表时出错: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/manga/search/{keyword}")
async def search_manga(keyword: str, page: int = 1):
"""
通过关键词搜索漫画
参数:
keyword: 搜索关键词
page: 页码,默认为1
"""
try:
if not keyword:
raise HTTPException(status_code=400, detail="搜索关键词不能为空")
logger.info(f"接收到搜索请求: keyword={keyword}, page={page}")
# 构建搜索URL
search_url = f"https://g-mh.org/s/{quote(keyword)}"
if page > 1:
search_url = f"{search_url}?page={page}"
# 尝试从缓存获取
cache_key = f'search_{keyword}_{page}'
cached_data = cache.get(cache_key)
if cached_data:
return {
'code': 200,
'message': 'success',
'data': cached_data,
'timestamp': int(datetime.now().timestamp())
}
# 首先尝试使用 cloudscraper
manga_list, pagination = await get_search_results_with_cloudscraper(search_url, page)
# 如果 cloudscraper 失败,尝试使用 playwright
if not manga_list:
logger.info("Cloudscraper失败,尝试使用Playwright")
manga_list, pagination = await get_search_results_with_playwright(search_url, page)
if not manga_list:
logger.warning("未找到漫画列表")
return {
'code': 200,
'message': '未找到搜索结果',
'data': {
'manga_list': [],
'pagination': {'current_page': page, 'page_links': []},
'keyword': keyword
},
'timestamp': int(datetime.now().timestamp())
}
result_data = {
'manga_list': manga_list,
'pagination': pagination,
'keyword': keyword
}
# 缓存结果
cache.set(cache_key, result_data)
logger.info(f"搜索成功,找到 {len(manga_list)} 个结果")
return {
'code': 200,
'message': 'success',
'data': result_data,
'timestamp': int(datetime.now().timestamp())
}
except Exception as e:
logger.error(f"搜索漫画时出错: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
class CloudflareSession:
_instance = None
_session = None
_last_verify_time = 0
_verify_interval = 300 # 5分钟验证一次
_lock = Lock()
_max_retries = 3
_retry_delay = 2 # 重试延迟(秒)
@classmethod
def get_instance(cls):
if not cls._instance:
with cls._lock:
if not cls._instance:
cls._instance = cls()
return cls._instance
def __init__(self):
self._create_session()
def _create_session(self):
try:
self._session = cloudscraper.create_scraper(
browser={
'browser': 'chrome',
'platform': 'darwin',
'mobile': False,
'desktop': True,
'custom': 'Chrome/122.0.0.0',
'app_version': '122.0.0.0',
'vendor': 'Google Inc.',
'renderer': 'WebKit',
'os_name': 'macOS',
'os_version': '10.15.7'
},
delay=10, # 增加延迟
interpreter='nodejs' # 使用nodejs解释器
)
# 更新请求头
self._session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Cache-Control': 'no-cache',
'Pragma': 'no-cache',
'Sec-Ch-Ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
'Sec-Ch-Ua-Mobile': '?0',
'Sec-Ch-Ua-Platform': '"Windows"',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
'Upgrade-Insecure-Requests': '1',
'Connection': 'keep-alive'
})
self._last_verify_time = time.time()
logger.info("成功创建Cloudflare会话")
except Exception as e:
logger.error(f"创建Cloudflare会话失败: {str(e)}")
raise
def _verify_session(self):
current_time = time.time()
if current_time - self._last_verify_time > self._verify_interval:
for attempt in range(self._max_retries):
try:
logger.info(f"验证 Cloudflare 会话 (尝试 {attempt + 1}/{self._max_retries})")
response = self._session.get('https://g-mh.org/', timeout=30)
if response.status_code == 200:
self._last_verify_time = current_time
logger.info("Cloudflare会话验证成功")
return
else:
logger.warning(f"Cloudflare会话验证失败,状态码: {response.status_code}")
if attempt < self._max_retries - 1:
logger.info(f"等待 {self._retry_delay} 秒后重试...")
time.sleep(self._retry_delay)
self._create_session()
else:
raise Exception(f"会话验证失败,已重试 {self._max_retries} 次")
except Exception as e:
logger.error(f"Cloudflare会话验证出错 (尝试 {attempt + 1}/{self._max_retries}): {str(e)}")
if attempt < self._max_retries - 1:
logger.info(f"等待 {self._retry_delay} 秒后重试...")
time.sleep(self._retry_delay)
self._create_session()
else:
raise
def get_session(self):
self._verify_session()
return self._session
def get(self, url, **kwargs):
"""发送GET请求,带重试机制"""
for attempt in range(self._max_retries):
try:
logger.info(f"发送 GET 请求到 {url} (尝试 {attempt + 1}/{self._max_retries})")
self._verify_session()
response = self._session.get(url, timeout=30, **kwargs)
if response.status_code == 200:
logger.info("请求成功")
return response
elif response.status_code == 403:
logger.warning(f"收到403响应,重新创建会话 (尝试 {attempt + 1}/{self._max_retries})")
self._create_session()
if attempt < self._max_retries - 1:
logger.info(f"等待 {self._retry_delay} 秒后重试...")
time.sleep(self._retry_delay)
continue
else:
logger.warning(f"请求失败,状态码: {response.status_code} (尝试 {attempt + 1}/{self._max_retries})")
if attempt < self._max_retries - 1:
logger.info(f"等待 {self._retry_delay} 秒后重试...")
time.sleep(self._retry_delay)
continue
return response
except Exception as e:
logger.error(f"请求失败 (尝试 {attempt + 1}/{self._max_retries}): {str(e)}")
if attempt < self._max_retries - 1:
logger.info(f"等待 {self._retry_delay} 秒后重试...")
time.sleep(self._retry_delay)
self._create_session()
else:
raise
cloudflare_session = CloudflareSession.get_instance()
async def get_page_content_with_cloudscraper():
"""使用 cloudscraper 获取页面内容"""
try:
# 设置代理配置
proxy_config = {
'http': 'http://127.0.0.1:7890',
'https': 'http://127.0.0.1:7890'
}
logger.info("创建 cloudscraper 会话...")
scraper = cloudscraper.create_scraper(
browser={
'browser': 'chrome',
'platform': 'darwin',
'mobile': False,
'desktop': True,
'custom': 'Chrome/122.0.0.0',
'app_version': '122.0.0.0',
'vendor': 'Google Inc.',
'renderer': 'WebKit',
'os_name': 'macOS',
'os_version': '10.15.7'
},
delay=10,
interpreter='nodejs'
)
# 设置代理
scraper.proxies = proxy_config
# 更新请求头
scraper.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Accept-Encoding': 'identity',
'Cache-Control': 'no-cache',
'Pragma': 'no-cache',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Ch-Ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
'Sec-Ch-Ua-Mobile': '?0',
'Sec-Ch-Ua-Platform': '"Windows"',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1'
})
# 发送请求
logger.info("使用 cloudscraper 访问网站...")
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(
None,
lambda: scraper.get(
'https://g-mh.org/',
allow_redirects=True,
timeout=60 # 延长超时时间
)
)
if response.status_code == 200:
logger.info("成功获取响应!")
# 检查响应内容
content = response.content
text = response.text
# 打印响应内容的前1000个字符用于调试
logger.debug(f"响应内容预览: {text[:1000]}")
# 检查响应内容是否包含预期的HTML结构
if '<html' not in text.lower():
logger.warning("响应内容可能不是有效的HTML")
return None
# 解析HTML
tree = etree.HTML(str(BeautifulSoup(content, 'html.parser')))
# 提取数据
logger.info("开始提取数据...")
updates = extract_updates(tree)
hot_updates = extract_hot_updates(tree)
popular = extract_popular_manga(tree)
new_manga = extract_new_manga(tree)
logger.info(f"找到 {len(updates)} 个最新更新")
logger.info(f"找到 {len(hot_updates)} 个热门更新")
logger.info(f"找到 {len(popular)} 个人气排行")
logger.info(f"找到 {len(new_manga)} 个最新上架")
# 返回所有数据
home_data = {
'updates': updates,
'hot_updates': hot_updates,
'popular_manga': popular,
'new_manga': new_manga
}
return home_data
else:
logger.warning(f"请求失败,状态码: {response.status_code}")
return None
except Exception as e:
logger.error(f"Cloudscraper 错误: {str(e)}")
import traceback
logger.error(f"错误堆栈:\n{traceback.format_exc()}")
return None
async def get_chapter_content_with_playwright(chapter_url: str) -> Tuple[List[str], Optional[str], Optional[str]]:
"""使用 Playwright 获取章节内容"""
try:
logger.info("初始化内容提取器...")
extractor = ContentExtractor(debug=True, headless=True)
result = await extractor.extract_content(chapter_url)
if result:
images = result.get('images', [])
if images:
logger.info(f"成功提取 {len(images)} 张图片")
return images, result.get('prev_chapter'), result.get('next_chapter')
else:
logger.warning("未找到任何图片")
else:
logger.warning("提取内容失败")
return [], None, None
except Exception as e:
logger.error(f"获取章节内容时出错: {str(e)}")
import traceback
logger.error(f"错误堆栈:\n{traceback.format_exc()}")
return [], None, None
def normalize_image_url(url: str) -> str:
"""标准化图片URL"""
if not url:
return ''
# 如果是相对路径,添加域名
if url.startswith('/'):
url = f'https://g-mh.org{url}'
elif not url.startswith(('http://', 'https://')):
url = f'https://g-mh.org/{url}'
return url
def normalize_manga_url(url: str) -> str:
"""标准化漫画URL"""
if not url:
return ''
# 如果是相对路径,添加域名
if url.startswith('/'):
url = f'https://g-mh.org{url}'
elif not url.startswith(('http://', 'https://')):
url = f'https://g-mh.org/{url}'
# 确保URL以/manga/开头
if '/manga/' not in url:
url = url.replace('https://g-mh.org/', 'https://g-mh.org/manga/')
return url
def extract_updates(tree) -> List[dict]:
"""提取最新更新列表"""
updates = []
try:
# 尝试不同的选择器
selectors = [
'//a[@class="slicarda"]',
'/html/body/main/div/div[4]/div/div[1]/a',
'/html/body/main/div/div[4]/div/div[2]/a'
]
for selector in selectors:
items = tree.xpath(selector)
logger.info(f"使用选择器 '{selector}' 找到 {len(items)} 个更新项")
if items:
for item in items:
try:
manga_info = {}
# 提取链接
href = item.get('href')
if href:
manga_info['link'] = normalize_image_url(href)
# 提取标题
title = item.xpath('.//h3[@class="slicardtitle"]/text()')
if title:
manga_info['title'] = title[0].strip()
# 提取时间
time_text = item.xpath('.//p[@class="slicardtagp"]/text()')
if time_text:
manga_info['time'] = time_text[0].strip()
# 提取章节
chapter = item.xpath('.//p[@class="slicardtitlep"]/text()')
if chapter:
manga_info['chapter'] = chapter[0].strip()
# 提取图片
img = item.xpath('.//img[@class="slicardimg"]')
if img:
src = img[0].get('src') or img[0].get('data-src')
if src:
manga_info['cover'] = normalize_image_url(src)
if manga_info.get('title') and manga_info.get('link'):
logger.info(f"找到更新: {manga_info['title']}")
updates.append(manga_info)
except Exception as e:
logger.error(f"处理更新项时出错: {str(e)}")
continue
# 如果找到了数据就不再尝试其他选择器
if updates:
break
return updates
except Exception as e:
logger.error(f"提取更新列表时出错: {str(e)}")
return []
def extract_hot_updates(tree) -> List[dict]:
"""提取热门更新列表"""
hot_updates = []
try:
# 尝试不同的选择器
selectors = [
'/html/body/main/div/div[6]/div[1]/div[2]/div',
'//div[contains(@class, "hot-updates")]//div[contains(@class, "manga-item")]',
'//div[contains(@class, "hot-section")]//a'
]
for selector in selectors:
items = tree.xpath(selector)
logger.info(f"使用选择器 '{selector}' 找到 {len(items)} 个热门更新")
if items:
for item in items:
try:
manga_info = {}
# 提取链接
link_elem = item.xpath('.//a')
if link_elem:
href = link_elem[0].get('href')
if href:
manga_info['link'] = normalize_image_url(href)
# 提取标题
title = item.xpath('.//h3/text()')
if title:
manga_info['title'] = title[0].strip()
# 提取图片
img = item.xpath('.//img')
if img:
src = img[0].get('src') or img[0].get('data-src')
if src:
manga_info['cover'] = normalize_image_url(src)
if manga_info.get('title') and manga_info.get('link'):
logger.info(f"找到热门更新: {manga_info['title']}")
hot_updates.append(manga_info)
except Exception as e:
logger.error(f"处理热门更新项时出错: {str(e)}")
continue
# 如果找到了数据就不再尝试其他选择器
if hot_updates:
break
return hot_updates
except Exception as e:
logger.error(f"提取热门更新列表时出错: {str(e)}")
return []
def extract_popular_manga(tree) -> List[dict]:
"""提取人气排行列表"""
popular = []
try:
# 尝试不同的选择器
selectors = [
'/html/body/main/div/div[6]/div[2]/div[2]/div',
'//div[contains(@class, "rank-section")]//div[contains(@class, "manga-item")]',
'//div[contains(@class, "popular-section")]//a'
]
for selector in selectors:
items = tree.xpath(selector)
logger.info(f"使用选择器 '{selector}' 找到 {len(items)} 个人气排行")
if items:
for index, item in enumerate(items, 1):
try:
manga_info = {}
# 提取链接
link_elem = item.xpath('.//a')
if link_elem:
href = link_elem[0].get('href')
if href:
manga_info['link'] = normalize_image_url(href)
# 提取标题
title = item.xpath('.//h3/text()')
if title:
manga_info['title'] = title[0].strip()
# 提取图片
img = item.xpath('.//img')
if img:
src = img[0].get('src') or img[0].get('data-src')
if src:
manga_info['cover'] = normalize_image_url(src)
# 添加排名
manga_info['rank'] = index
if manga_info.get('title') and manga_info.get('link'):
logger.info(f"找到人气排行: {manga_info['title']} (第{index}名)")
popular.append(manga_info)
except Exception as e:
logger.error(f"处理人气排行项时出错: {str(e)}")
continue
# 如果找到了数据就不再尝试其他选择器
if popular:
break
return popular
except Exception as e:
logger.error(f"提取人气排行列表时出错: {str(e)}")
return []
def extract_new_manga(tree) -> List[dict]:
"""提取最新上架列表"""
new_manga = []
try:
# 尝试不同的选择器
selectors = [
'/html/body/main/div/div[6]/div[3]/div[2]/div',
'//div[contains(@class, "new-manga")]//div[contains(@class, "manga-item")]',
'//div[contains(@class, "new-section")]//a'
]
for selector in selectors:
items = tree.xpath(selector)
logger.info(f"使用选择器 '{selector}' 找到 {len(items)} 个最新上架")
if items:
for item in items:
try:
manga_info = {}
# 提取链接
link_elem = item.xpath('.//a')
if link_elem:
href = link_elem[0].get('href')
if href:
manga_info['link'] = normalize_image_url(href)
# 提取标题
title = item.xpath('.//h3/text()')
if title:
manga_info['title'] = title[0].strip()