forked from MakeYourLifeEasier/Wuxiaworld-2-eBook
-
Notifications
You must be signed in to change notification settings - Fork 4
/
NovelParsers.py
969 lines (626 loc) · 34.6 KB
/
NovelParsers.py
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
from bs4 import BeautifulSoup
from multiprocessing.pool import ThreadPool
import PageTools
from PIL import Image
from io import BytesIO
import re
import requests
import json
import gc
noCoverLink = "http://admin.johnsons.net/janda/files/flipbook-coverpage/nocoverimg.jpg"
class WuxiaWorldParser:
def __init__(self):
self.url = "https://www.wuxiaworld.com"
self.name = "Wuxia World"
self.jsonFile = None
self.novels = None
self.novelNames = None
self.novelSypnoses = None
self.isLoaded = False
self.bsParser = "lxml"
# Container for all novels that are requested
self.novelLibrary = {}
def load(self):
if not self.isLoaded:
# Download and parse the WuxiaWorld API JSON file
url = self.url+"/api/novels/search"
payload = '{"title":"","tags":[],"language":"Any","genres":[],"active":null,"sortType":"Name","sortAsc":false,"searchAfter":null,"count":500}'
self.jsonFile = PageTools.getJsonFromPost(url,payload)
self.parseNovelList()
self.isLoaded = True
def clearNovelCache(self):
self.novelLibrary = {}
def insertSpecialCases(self):
# del self.novels['Absolute Resonance']
pass
# self.novels["Trash of the Count's Family"] = ["https://www.wuxiaworld.com/novel/trash-of-the-counts-family","https://cdn.wuxiaworld.com/images/covers/tcf.jpg","miraclerifle","TCF"]
# self.novels["The Novel's Extra"] = ["https://www.wuxiaworld.com/novel/the-novels-extra","https://cdn.wuxiaworld.com/images/covers/tne.jpg","FudgeNouget","TNE"]
# self.novels["Stop, Friendly Fire!"] = ["https://www.wuxiaworld.com/novel/stop-friendly-fire","https://cdn.wuxiaworld.com/images/covers/sff.jpg","Boko","SFF"]
# self.novels["Sage Monarch"] = ["https://www.wuxiaworld.com/novel/sage-monarch","https://cdn.wuxiaworld.com/images/covers/sm.jpg","Deathblade","SM"]
# self.novels["Nine Star Hegemon Body Art"] = ["https://www.wuxiaworld.com/novel/nine-star-hegemon","https://cdn.wuxiaworld.com/images/covers/nshba.jpg","BornToBe","NSHBA"]
# self.novels["Dragon Prince Yuan"] = ["https://www.wuxiaworld.com/novel/dragon-prince-yuan","https://cdn.wuxiaworld.com/images/covers/yz.jpg","Yellowlaw","DPY"]
# self.novels["Coiling Dragon"] = ["https://www.wuxiaworld.com/novel/coiling-dragon-preview","https://cdn.wuxiaworld.com/images/covers/cdp.jpg","RWX","CDP"]
# self.novelSypnoses["Trash of the Count's Family"] = "N/A"
# self.novelSypnoses["The Novel's Extra"] = "N/A"
# self.novelSypnoses["Stop, Friendly Fire!"] = "N/A"
# self.novelSypnoses["Sage Monarch"] = "N/A"
# self.novelSypnoses["Nine Star Hegemon Body Art"] = "N/A"
# self.novelSypnoses["Dragon Prince Yuan"] = "N/A"
# self.novelSypnoses["Coiling Dragon"] = "N/A"
def parseNovelList(self):
# Handle key error if the novel doesn't have a sypnosis
def checkForSypnosis(novel):
try:
novel['sypnosis']
except KeyError:
return False
return True
# Extract the required novel info
self.novels = {novel['name']:[self.url+"/novel/"+novel['slug'], novel['coverUrl'], novel['id']] for novel in self.jsonFile['items']}
self.novelSypnoses = {novel['name']:(novel['sypnosis'] if checkForSypnosis(novel) else "N/A") for novel in self.jsonFile['items']}
self.insertSpecialCases()
self.novelNames = list(self.novels.keys())
self.novelNames.sort()
def loadNovelInfo(self, novelName):
if novelName in self.novelLibrary.keys():
return
elif novelName == "Coiling Dragon":
# Load the webpage for the novel
soup = PageTools.getSoupFromUrl(self.novels[novelName][0])
# Create a dummy book
bookTitles = ["Preview"]
# Create an empty dictionary to store all chapter names and links
chapterLibrary = []
bookToC = {}
# Extract the html containing the chapter links and names
chapterInfo = PageTools.getElementsFromSoup(soup,[{"class_":"section"},\
{"class_":"list-unstyled"},"li"], findAllEnableList = True)
# Extract the chapter links and names
chapterInfo = [[PageTools.getElementsFromSoup(chap, ["a"], findAllEnableList=True)[0]['href'],\
PageTools.getElementsFromSoup(chap, ["a"], findAllEnableList=True, onlyText=True)[0].replace("<",'').replace(">",'')] for chap in chapterInfo]
chapterInfo = chapterInfo[0:3]
# Store chapters for each book
bookToC["Preview"] = chapterInfo
chapterLibrary.extend(bookToC["Preview"])
# Download cover image
try:
coverImage = PageTools.downloadPage(self.novels[novelName][1])
except:
coverImage = PageTools.downloadPage(noCoverLink)
# Add the books, chapters, and the cover to the novel library
self.novelLibrary[novelName] = [bookTitles, chapterLibrary, bookToC, coverImage]
return
# Load the webpage for the novel
soup = PageTools.getSoupFromUrl(self.novels[novelName][0])
# Parse all of the book names/sections
bookTitles = PageTools.getElementsFromSoup(soup, [{"id":"accordion"},{"class_":"title"}], onlyText = True)
# Download cover image
try:
coverImage = PageTools.downloadPage(self.novels[novelName][1])
except:
coverImage = PageTools.downloadPage("http://admin.johnsons.net/janda/files/flipbook-coverpage/nocoverimg.jpg")
# Create an empty dictionary to store all chapter names and links
chapterLibrary = []
bookToC = {}
for i, bookTitle in enumerate(bookTitles):
# Extract the html containing the chapter links and names
chapterInfo = PageTools.getElementsFromSoup(soup,[{"id":"collapse-{}".format(i)},\
{"class_":"row"},{"class_":"col-sm-6"},{"class_":"chapter-item"}])
# Extract the chapter links and names
chapterInfo = [[self.url+PageTools.getElementsFromSoup(chap, ["a"])[0]['href'],\
PageTools.getElementsFromSoup(chap, ["a"], onlyText=True)[0].replace("<",'').replace(">",'')] for chap in chapterInfo]
# Store chapters for each book
bookToC[bookTitle] = chapterInfo
chapterLibrary.extend(bookToC[bookTitle])
# Add the books, chapters, and the cover to the novel library
self.novelLibrary[novelName] = [bookTitles, chapterLibrary, bookToC, coverImage]
def getNovelNames(self):
self.load()
return self.novelNames
def getImageBinary(self, novelName):
self.loadNovelInfo(novelName)
return self.novelLibrary[novelName][3]
def getImagePillow(self, novelName):
return Image.open(BytesIO(self.getImageBinary(novelName)))
def getNovelBookNames(self, novelName):
self.loadNovelInfo(novelName)
return self.novelLibrary[novelName][0]
def getNovelChapterLinks(self, novelName):
self.loadNovelInfo(novelName)
return [chapter[0] for chapter in self.novelLibrary[novelName][1]]
def getNovelChapterNames(self, novelName):
self.loadNovelInfo(novelName)
return [chapter[1] for chapter in self.novelLibrary[novelName][1]]
def getNovelBookChapterLinks(self, novelName, bookName):
self.loadNovelInfo(novelName)
return [chapter[0] for chapter in self.novelLibrary[novelName][2][bookName]]
def getNovelBookChapterNames(self, novelName, bookName):
self.loadNovelInfo(novelName)
return [chapter[1] for chapter in self.novelLibrary[novelName][2][bookName]]
def cleanChapter(self, soup):
hasSpoiler = None
# Extract the chapter title and the chapter content
chapterTitle = soup.find(class_="caption clearfix")
content = chapterTitle.find_next_sibling(class_="fr-view")
chapterTitle = chapterTitle.find("h4")
# Get the chapter title, make it hidden if it contains spoilers
try:
if chapterTitle.attrs["class"][0] == "text-spoiler":
hasSpoiler = chapterTitle.text
chapterTitle = "Chapter name hidden due to potential spoilers"
else:
chapterTitle = chapterTitle.text
except IndexError:
chapterTitle = chapterTitle.text
# Remove characters that might corrupt the ebook file
chapterTitle = chapterTitle.replace("<",'<').replace(">",'>')
for a in content.find_all("a"):
a.decompose()
# Add html header to the chapter
chapter = '<html xmlns="http://www.w3.org/1999/xhtml">\n<head>\n<title>{0}</title>\n</head>\n<body>\n<h1>{0}</h1>\n'.format(chapterTitle)
chapter += str(content)
if hasSpoiler != None:
chapter += "<strong>The chapter name is: {}</strong>".format(hasSpoiler)
# Collect some garbage to reduce RAM usage
soup = None
chapterTitle = None
content = None
gc.collect()
# Return the chapter as a BeautifulSoup html object
return BeautifulSoup(chapter, "html.parser")
class VolareNovelsParser:
def __init__(self):
self.url = "https://www.volarenovels.com"
self.name = "Volare Novels"
# Download and parse the Volare Novels API JSON file
self.jsonFile = None
# url = self.url+"/api/novels/search"
# payload = '{"title":"","language":null,"tags":[],"active":null,"sortType":"Name","sortAsc":true,"searchAfter":null,"count":500}'
# self.jsonFile = PageTools.getJsonFromPost(url,payload)
self.novels = None
self.novelNames = None
self.novelSypnoses = None
self.isLoaded = False
self.bsParser = "html.parser"
# Container for all novels that are requested
self.novelLibrary = {}
def load(self):
if not self.isLoaded:
self.jsonFile = PageTools.getJsonFromUrl(self.url+"/api/novels")
self.parseNovelList()
self.isLoaded = True
def clearNovelCache(self):
self.novelLibrary = {}
def insertSpecialCases(self):
pass
def parseNovelList(self):
# Handle key error if the novel doesn't have a sypnosis
def checkForSypnosis(novel):
try:
novel['sypnosis']
except KeyError:
return False
return True
# Extract the required novel info
self.novels = {novel['name']:[self.url+"/novel/"+novel['slug'], novel['coverUrl'], novel['translatorUserName']] for novel in self.jsonFile['items']}
self.novelSypnoses = {novel['name']:(novel['sypnosis'] if checkForSypnosis(novel) else "N/A") for novel in self.jsonFile['items']}
self.insertSpecialCases()
self.novelNames = list(self.novels.keys())
self.novelNames.sort()
def loadNovelInfo(self, novelName):
if novelName in self.novelLibrary.keys():
return
# Load the webpage for the novel
soup = PageTools.getSoupFromUrl(self.novels[novelName][0])
# Parse all of the book names/sections
bookTitles = PageTools.getElementsFromSoup(soup, [{"id":"accordion"},{"class_":"title"}], onlyText = True)
# Download cover image
try:
coverImage = PageTools.downloadPage(self.novels[novelName][1])
except:
coverImage = PageTools.downloadPage(noCoverLink)
# Create an empty dictionary to store all chapter names and links
chapterLibrary = []
bookToC = {}
bookTitles = [bookTitle.strip(" ").strip("\n") for bookTitle in bookTitles]
for i, bookTitle in enumerate(bookTitles):
# Extract the html containing the chapter links and names
chapterInfo = PageTools.getElementsFromSoup(soup,[{"id":"collapse-{}".format(i)},\
{"class_":"row"},{"class_":"col-sm-6"},{"class_":"chapter-item"}])
# Extract the chapter links and names
chapterInfo = [[self.url+PageTools.getElementsFromSoup(chap, ["a"])[0]['href'],\
PageTools.getElementsFromSoup(chap, ["a"], onlyText=True)[0].replace("<",'').replace(">",'')] for chap in chapterInfo]
# Store chapters for each book
bookToC[bookTitle ] = chapterInfo
chapterLibrary.extend(bookToC[bookTitle])
# Add the books, chapters, and the cover to the novel library
self.novelLibrary[novelName] = [bookTitles, chapterLibrary, bookToC, coverImage]
def getNovelNames(self):
self.load()
return self.novelNames
def getImageBinary(self, novelName):
self.loadNovelInfo(novelName)
return self.novelLibrary[novelName][3]
def getImagePillow(self, novelName):
return Image.open(BytesIO(self.getImageBinary(novelName)))
def getNovelBookNames(self, novelName):
self.loadNovelInfo(novelName)
return self.novelLibrary[novelName][0]
def getNovelChapterLinks(self, novelName):
self.loadNovelInfo(novelName)
return [chapter[0] for chapter in self.novelLibrary[novelName][1]]
def getNovelChapterNames(self, novelName):
self.loadNovelInfo(novelName)
return [chapter[1] for chapter in self.novelLibrary[novelName][1]]
def getNovelBookChapterLinks(self, novelName, bookName):
self.loadNovelInfo(novelName)
return [chapter[0] for chapter in self.novelLibrary[novelName][2][bookName]]
def getNovelBookChapterNames(self, novelName, bookName):
self.loadNovelInfo(novelName)
return [chapter[1] for chapter in self.novelLibrary[novelName][2][bookName]]
def cleanChapter(self, soup):
hasSpoiler = None
# Extract the chapter title and the chapter content
chapterTitle = soup.find(class_="caption clearfix")
content = chapterTitle.find_next_sibling(class_="jfontsize_content fr-view")
chapterTitle = chapterTitle.find("h4")
# Get the chapter title, make it hidden if it contains spoilers
try:
if chapterTitle.attrs["class"][0] == "text-spoiler":
hasSpoiler = chapterTitle.text
chapterTitle = "Chapter name hidden due to potential spoilers"
else:
chapterTitle = chapterTitle.text
except IndexError:
chapterTitle = chapterTitle.text
# Remove characters that might corrupt the ebook file
chapterTitle = chapterTitle.replace("<",'<').replace(">",'>')
for a in content.find_all("a"):
a.decompose()
# Add html header to the chapter
chapter = '<html xmlns="http://www.w3.org/1999/xhtml">\n<head>\n<title>{0}</title>\n</head>\n<body>\n<h1>{0}</h1>\n'.format(chapterTitle)
chapter += str(content)
if hasSpoiler != None:
chapter += "<strong>The chapter name is: {}</strong>".format(hasSpoiler)
# Collect some garbage to reduce RAM usage
soup = None
chapterTitle = None
content = None
gc.collect()
# Return the chapter as a BeautifulSoup html object
return BeautifulSoup(chapter, "html.parser")
class TotallyTranslationsParser:
def __init__(self):
self.url = "https://totallytranslations.com"
self.name = "Totally Translations"
# Create containers
self.novels = {}
self.novelNames = None
# self.novelSypnoses = None
self.isLoaded = False
self.bsParser = "html.parser"
# Container for all novels that are requested
self.novelLibrary = {}
def load(self):
if not self.isLoaded:
self.parseNovelList()
self.isLoaded = True
def clearNovelCache(self):
self.novelLibrary = {}
def insertSpecialCases(self):
pass
def parseNovelList(self):
novels = PageTools.getElementsFromUrl(self.url, [ {"class_":"col-md-6"}, {"class_":"slide"}], [False, True])
for novel in novels:
title = PageTools.getElementsFromSoup(novel, [ {"class_":"slide-description"}, "strong"], onlyText=True)[0]
novelLink = PageTools.getElementsFromSoup(novel, [ {"class_":"slide-image"}, "a"])[0]
imgLink = PageTools.getElementsFromSoup(novelLink, ["img"])[0]['src']
self.novels[title] = [novelLink['href'], imgLink, "N/A"]
self.insertSpecialCases()
self.novelNames = list(self.novels.keys())
self.novelNames.sort()
def loadNovelInfo(self, novelName):
if novelName in self.novelLibrary.keys():
return
# Load the webpage for the novel
soup = PageTools.getElementsFromUrl(self.novels[novelName][0], [{"class_":"chapters-list"}])[0]
titles = PageTools.getElementsFromSoup(soup, [{"class_":"chapters-title"}], onlyText=True)
chapterBlocks = PageTools.getElementsFromSoup(soup, [{"class_":"clearfix chapters-acc"}])
# Download cover image
try:
coverImage = PageTools.downloadPage(self.novels[novelName][1])
except:
coverImage = PageTools.downloadPage(noCoverLink)
# Create an empty dictionary to store all chapter names and links
chapterLibrary = []
bookToC = {}
for title, chapterBlock in zip(titles, chapterBlocks):
chapters = PageTools.getElementsFromSoup(chapterBlock, ["a"])
chapterInfo = [[chapter['href'], chapter.string.replace("<",'').replace(">",'')] for chapter in chapters]
# Store chapters for each book
bookToC[title] = chapterInfo
chapterLibrary.extend(bookToC[title])
# Add the books, chapters, and the cover to the novel library
self.novelLibrary[novelName] = [titles, chapterLibrary, bookToC, coverImage]
def getNovelNames(self):
self.load()
return self.novelNames
def getImageBinary(self, novelName):
self.loadNovelInfo(novelName)
return self.novelLibrary[novelName][3]
def getImagePillow(self, novelName):
return Image.open(BytesIO(self.getImageBinary(novelName)))
def getNovelBookNames(self, novelName):
self.loadNovelInfo(novelName)
return self.novelLibrary[novelName][0]
def getNovelChapterLinks(self, novelName):
self.loadNovelInfo(novelName)
return [chapter[0] for chapter in self.novelLibrary[novelName][1]]
def getNovelChapterNames(self, novelName):
self.loadNovelInfo(novelName)
return [chapter[1] for chapter in self.novelLibrary[novelName][1]]
def getNovelBookChapterLinks(self, novelName, bookName):
self.loadNovelInfo(novelName)
return [chapter[0] for chapter in self.novelLibrary[novelName][2][bookName]]
def getNovelBookChapterNames(self, novelName, bookName):
self.loadNovelInfo(novelName)
return [chapter[1] for chapter in self.novelLibrary[novelName][2][bookName]]
def cleanChapter(self, soup):
hasSpoiler = None
# Extract the chapter title and the chapter content
chapterTitle = soup.find(class_="entry-title fusion-post-title").string
content = soup.find(class_="post-content")
# Remove characters that might corrupt the ebook file
chapterTitle = chapterTitle.replace("<",'<').replace(">",'>')
for a in content.find_all("a"):
a.decompose()
for button in content.find_all("button"):
button.decompose()
# Add html header to the chapter
chapter = '<html xmlns="http://www.w3.org/1999/xhtml">\n<head>\n<title>{0}</title>\n</head>\n<body>\n<h1>{0}</h1>\n'.format(chapterTitle)
chapter += str(content)
if hasSpoiler != None:
chapter += "<strong>The chapter name is: {}</strong>".format(hasSpoiler)
# Collect some garbage to reduce RAM usage
soup = None
chapterTitle = None
content = None
gc.collect()
# Return the chapter as a BeautifulSoup html object
return BeautifulSoup(chapter, "html.parser")
class NovelleLeggereParser:
def __init__(self):
self.url = "https://www.novelleleggere.com/"
self.name = "Novelle Leggere"
# Create containers
self.novels = {}
self.novelNames = None
# self.novelSypnoses = None
self.isLoaded = False
self.bsParser = "lxml"
# Container for all novels that are requested
self.novelLibrary = {}
def load(self):
if not self.isLoaded:
self.parseNovelList()
self.isLoaded = True
def clearNovelCache(self):
self.novelLibrary = {}
def insertSpecialCases(self):
del self.novels["The Legend of Randidly Ghosthound"]
pass
def parseNovelList(self):
tables = PageTools.getElementsFromUrl(self.url, ["table"])
tables = tables[0:2]
for table in tables:
novels = PageTools.getElementsFromSoup(table, ["strong","a"])
for novel in novels:
title = novel.text.strip()
self.novels[title] = [novel['href'], "N/A", "N/A"]
self.insertSpecialCases()
self.novelNames = list(self.novels.keys())
self.novelNames.sort()
def loadNovelInfo(self, novelName):
if novelName in self.novelLibrary.keys():
return
# Load the webpage for the novel
soup = PageTools.getElementsFromUrl(self.novels[novelName][0], [{"id":"content"}],parser = 'lxml')[0]
titles = PageTools.getElementsFromSoup(soup, [{"class_":"su-spoiler-title"}], onlyText=True)
chapterBlocks = PageTools.getElementsFromSoup(soup, [{"class_":"display-posts-listing"}])
self.novels[novelName][1] = PageTools.getElementsFromSoup(soup,["img"])[0]['src']
# Special parsing conditions
if novelName == "The Wandering Inn":
titles = titles[4:]
elif novelName == "Il Demone Contro il Cielo":
titles = titles[1:]
chapterBlocks = PageTools.getElementsFromSoup(soup, [{"class_":"su-spoiler-content su-u-clearfix su-u-trim"}])
else:
titles = titles[2:]
if novelName == "Legendary Moonlight Sculptor":
chapterBlocks = PageTools.getElementsFromSoup(soup, [{"class_":"su-spoiler-content su-u-clearfix su-u-trim"}])
chapterBlocks = chapterBlocks[2:]
# Download cover image
try:
coverImage = PageTools.downloadPage(self.novels[novelName][1])
except:
coverImage = PageTools.downloadPage(noCoverLink)
# Create an empty dictionary to store all chapter names and links
chapterLibrary = []
bookToC = {}
for title, chapterBlock in zip(titles, chapterBlocks):
chapters = PageTools.getElementsFromSoup(chapterBlock, ["a"])
chapterInfo = [[chapter['href'], chapter.string.replace("<",'').replace(">",'')] for chapter in chapters]
# Store chapters for each book
bookToC[title] = chapterInfo
chapterLibrary.extend(bookToC[title])
# Add the books, chapters, and the cover to the novel library
self.novelLibrary[novelName] = [titles, chapterLibrary, bookToC, coverImage]
def getNovelNames(self):
self.load()
return self.novelNames
def getImageBinary(self, novelName):
self.loadNovelInfo(novelName)
return self.novelLibrary[novelName][3]
def getImagePillow(self, novelName):
return Image.open(BytesIO(self.getImageBinary(novelName)))
def getNovelBookNames(self, novelName):
self.loadNovelInfo(novelName)
return self.novelLibrary[novelName][0]
def getNovelChapterLinks(self, novelName):
self.loadNovelInfo(novelName)
return [chapter[0] for chapter in self.novelLibrary[novelName][1]]
def getNovelChapterNames(self, novelName):
self.loadNovelInfo(novelName)
return [chapter[1] for chapter in self.novelLibrary[novelName][1]]
def getNovelBookChapterLinks(self, novelName, bookName):
self.loadNovelInfo(novelName)
return [chapter[0] for chapter in self.novelLibrary[novelName][2][bookName]]
def getNovelBookChapterNames(self, novelName, bookName):
self.loadNovelInfo(novelName)
return [chapter[1] for chapter in self.novelLibrary[novelName][2][bookName]]
def cleanChapter(self, soup):
hasSpoiler = None
# Extract the chapter title and the chapter content
chapterTitle = soup.find(class_="entry-title fusion-post-title").string
content = soup.find(class_="post-content")
# Remove characters that might corrupt the ebook file
chapterTitle = chapterTitle.replace("<",'<').replace(">",'>')
# Remove unnecessary objects and ads from the chapter
for obj in content.find_all(**{"data-type":"post"}):
obj.decompose()
for n in content.find_all(class_="su-note"):
n.decompose()
for i in range(1,10):
for ad in content.find_all(class_="quads-location quads-ad{}".format(i)):
ad.decompose()
# Add html header to the chapter
chapter = '<html xmlns="http://www.w3.org/1999/xhtml">\n<head>\n<title>{0}</title>\n</head>\n<body>\n<h1>{0}</h1>\n'.format(chapterTitle)
chapter += str(content)
if hasSpoiler != None:
chapter += "<strong>The chapter name is: {}</strong>".format(hasSpoiler)
# Collect some garbage to reduce RAM usage
soup = None
chapterTitle = None
content = None
gc.collect()
# Return the chapter as a BeautifulSoup html object
return BeautifulSoup(chapter, "html.parser")
class ReadLightNovelParser:
def __init__(self):
self.url = "https://www.readlightnovel.org/"
self.name = "Read Light Novel"
# Create containers
self.novels = {}
self.novelNames = None
self.novelSypnoses = {}
self.isLoaded = False
self.bsParser = "html.parser"
# Container for all novels that are requested
self.novelLibrary = {}
def load(self):
if not self.isLoaded:
self.parseNovelList()
self.isLoaded = True
def clearNovelCache(self):
self.novelLibrary = {}
def parseNovelList(self):
#soup = PageTools.getSoupFromUrl(self.url+"novel-list", parser="html5lib")
letters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
links = [self.url+"novel-list/"+letter for letter in letters]
poolSize = len(letters)
letters = []
def downloadPage(link):
letters.append(PageTools.getSoupFromUrl(link, parser="html5lib"))
with ThreadPool(poolSize) as pool:
pool.map(downloadPage, links, chunksize=1)
for soup in letters:
books = PageTools.getElementsFromSoup(soup,[{"class_":"col-lg-12"},{"class_":"list-by-word-body"},"li"])
for book in books:
if PageTools.getElementsFromSoup(book, ["a"])[0]['href'] == "#":
continue
linkTitle = PageTools.getElementsFromSoup(book, [{"data-toggle":"popover"}])[0]
self.novels[linkTitle.string] = [linkTitle['href'], PageTools.getElementsFromSoup(book, ["img"])[0]['src'], "N/A"]
self.novelSypnoses[linkTitle.string] = PageTools.getElementsFromSoup(book, [{"class_":"pop-summary"}], onlyText=True)[0]
self.novelNames = list(self.novels.keys())
self.novelNames.sort()
def loadNovelInfo(self, novelName):
if novelName in self.novelLibrary.keys():
return
# Load the webpage for the novel
soup = PageTools.getSoupFromUrl(self.novels[novelName][0])
# Download cover image
try:
coverImage = PageTools.downloadPage(self.novels[novelName][1])
except:
coverImage = PageTools.downloadPage(noCoverLink)
# Parse all of the book names/sections
bookTitles = PageTools.getElementsFromSoup(soup, [{"id":"accordion"},{"class_":"panel-title"}], onlyText = True)
# Create an empty dictionary to store all chapter names and links
chapterLibrary = []
bookToC = {}
for i, bookTitle in enumerate(bookTitles):
# Extract the html containing the chapter links and names
chapterInfo = PageTools.getElementsFromSoup(soup,[{"id":"collapse-{}".format(i+1)},{"class_":"chapter-chs"},"a"])
# Extract the chapter links and names
chapterInfo = [[chap['href'], bookTitle+", "+chap.string.replace("<",'').replace(">",'')] for chap in chapterInfo]
# Store chapters for each book
bookToC[re.sub("\n", "", bookTitle)] = chapterInfo
chapterLibrary.extend(bookToC[bookTitle])
# Add the books, chapters, and the cover to the novel library
self.novelLibrary[novelName] = [bookTitles, chapterLibrary, bookToC, coverImage]
def getNovelNames(self):
self.load()
return self.novelNames
def getImageBinary(self, novelName):
self.loadNovelInfo(novelName)
return self.novelLibrary[novelName][3]
def getImagePillow(self, novelName):
return Image.open(BytesIO(self.getImageBinary(novelName)))
def getNovelBookNames(self, novelName):
self.loadNovelInfo(novelName)
return self.novelLibrary[novelName][0]
def getNovelChapterLinks(self, novelName):
self.loadNovelInfo(novelName)
return [chapter[0] for chapter in self.novelLibrary[novelName][1]]
def getNovelChapterNames(self, novelName):
self.loadNovelInfo(novelName)
return [chapter[1] for chapter in self.novelLibrary[novelName][1]]
def getNovelBookChapterLinks(self, novelName, bookName):
self.loadNovelInfo(novelName)
return [chapter[0] for chapter in self.novelLibrary[novelName][2][bookName]]
def getNovelBookChapterNames(self, novelName, bookName):
self.loadNovelInfo(novelName)
return [chapter[1] for chapter in self.novelLibrary[novelName][2][bookName]]
def cleanChapter(self, soup):
# Extract the chapter title and the chapter content
content = soup.find(class_="desc")
# Remove characters that might corrupt the ebook file
chapterTitle = re.search("Chapter \d*", content.decode_contents()).group()
elements = ["ads-title","apester-element"]
for element in elements:
for script in content.find_all(class_=element):
script.decompose()
for a in content.find_all("a"):
a.decompose()
for hr in content.find_all("hr"):
hr.decompose()
for script in content.find_all("script"):
script.decompose()
for div in content.find_all("div"):
div.decompose()
chapContent = content.decode_contents()
chapContent = re.sub("<br>", "", chapContent)
chapContent = re.sub("</br>", "", chapContent)
# Add html header to the chapter
chapter = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html>\n\n"
chapter += '<html xmlns="http://www.w3.org/1999/xhtml">\n<head>\n<title>{0}</title>\n</head>\n<body>\n<h1>{0}</h1>\n'.format(chapterTitle)
chapter += re.sub(" \.", ".", chapContent).strip("\n"+chapterTitle)
# Collect some garbage to reduce RAM usage
soup = None
chapterTitle = None
content = None
gc.collect()
# Return the chapter as a BeautifulSoup html object
return BeautifulSoup(chapter, "html.parser")
if __name__ == "__main__":
pass