forked from LucasRMehl/wuxiaworld_scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wuxiaworld_scraper.py
266 lines (226 loc) · 10.1 KB
/
wuxiaworld_scraper.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
#!/usr/bin/env python
import sys
import re
import time
import codecs
import requests
from bs4 import BeautifulSoup
reload(sys)
sys.setdefaultencoding('utf-8')
def process_index_page(url):
''' Processes the index page, returns the title, description, and starting
element for BeautifulSoup parsing '''
# Get source of index page and load into BS
r_idx = requests.get(url)
print "Default encoding: {}, forcing utf-8".format(r_idx.encoding)
r_idx.encoding = 'utf-8'
soup = BeautifulSoup(r_idx.text, 'html.parser')
# Extract book name and links to chapters
# Start with the entry-content div and go down from there
start = soup.find('h1', {'class': 'entry-title'})
# Grab the title (the English part before the "(")
title = start.text.split('(')[0].strip()
print "Fetching {}...".format(title)
# Grab the description
desc = start.find_next("p").text
return (title, desc, start)
def process_chapter_page(ch_url, ch_num, out, debug):
''' Processes the chapter itself '''
r_chap = requests.get(ch_url)
r_chap.encoding = 'utf-8'
ch_soup = BeautifulSoup(r_chap.text, 'html.parser')
first_el = ch_soup.find(True)
this_strong = first_el
this_bold = first_el
tmp = ''
# Get backup title
try:
backup_title = ch_soup.find('h1', {'class': 'entry-title'}).text.strip()
except:
backup_title = 'Ch. {}'.format(ch_num)
ch_title = ''
while not ch_title:
if this_strong:
try:
this_strong = this_strong.find_next("strong")
tmp = this_strong.text.strip()
except AttributeError:
pass
elif this_bold:
try:
this_bold = this_bold.find_next("b")
tmp = this_bold.text.strip()
except AttributeError:
pass
else:
print "Could not find any strong or bold elements with the title inside!"
print "Going with backup title..."
tmp = backup_title
try:
if debug:
print "DEBUG: strong element found: {}".format(tmp)
# Skip formatting when using backup title
if tmp == backup_title:
ch_title = tmp
# Coiling Dragon- and Against the Gods-style chapter titles
elif "Chapter" in tmp.split():
ch_title = tmp[tmp.find("Chapter"):].replace("Chapter", "Ch.")
continue
# Stellar Transformations-style chapter titles
elif re.match('B[0-9]+C[0-9]+', tmp):
ch_title = re.sub('B[0-9]+C', 'Ch. ', tmp)
# Handle prologue
elif tmp.split()[0] in ("Prologue"):
ch_title = tmp
# Handle stupid HTML in Stellar Transformations Chapter Ones
elif "Book" in tmp.split():
# Get next element text, which should be B[0-9]+C[0-9]+
tmp = this_strong.find_next(True).text.strip()
if re.match('B[0-9]+C[0-9]+', tmp):
ch_title = re.sub('B[0-9]+C', 'Ch. ', tmp)
else:
continue
except IndexError:
pass
# Put chapter title in h1 so the epub converter will see it as a chapter
if debug:
print "DEBUG: Chapter title found: {}".format(ch_title)
else:
sys.stdout.write("Processing Ch. {}...\r".format(ch_num))
sys.stdout.flush()
out.write('\n\n<h1>{}</h1>\n'.format(ch_title))
# Then loop through each next element and plop it in there
# until we hit a horizontal rule
start_tag = ch_soup.find("hr")
start_tag = start_tag.find_next(True)
for p in start_tag.find_all_next(True):
if p.name == "hr":
break
elif "Previous Chapter" in p.text and "Next Chapter" in p.text:
break
elif p.name == "p":
out.write(unicode(p))
out.write("\n")
def run_pandoc_on(filenames):
''' Runs pandoc on the resulting html files '''
import subprocess
for fn in filenames:
try:
cmdl = ['pandoc', '-f', 'html', '-t', 'epub', fn,
'-o', fn.replace('.html', '.epub')]
print "Command: {}".format(" ".join(cmdl))
subprocess.call(cmdl)
print 'Successfully converted {} to epub!'.format(fn)
except subprocess.CalledProcessError:
print 'Converting to epub failed for {}. Skipping...'.format(fn)
def scrape(url, books, delay, skip_epub, debug):
''' Scrapes the given URL and creates combined HTML file '''
# Process index page
if debug:
print "DEBUG: Processing chapter index at URL:"
print "DEBUG: {}".format(url)
title, desc, start = process_index_page(url)
# Save filenames for conversion later
fnames = []
# book names are between <strong> tags
for elem in start.find_all_next(['strong', 'b']):
# Book: Coiling Dragon/Stellar Transformations
# Volume: Against the Gods, MArtial God Asura
try:
first_word = elem.text.split()[0]
except IndexError:
continue
if first_word in ("Book", "Volume"):
# Skip unwanted books/volumes
booknum = elem.text.split()[1].strip(':')
if books and int(booknum) not in books:
print "Skipping Book {}...".format(booknum)
continue
print "Processing Book {}".format(booknum)
# This is a book! Open a new HTML file and write some metadata
fname = ("".join(title.split()) + elem.text.split()[0] +
elem.text.split()[1].strip(":").zfill(2) + ".html")
fnames.append(fname)
# Use codecs.open to ensure we maintain unicode throughout
if debug:
print "DEBUG: Opening file {}".format(fname)
with codecs.open(fname, 'w', 'utf-8') as out:
html_title = title + ": " + elem.text
out.write(('<html>\n<head>\n<meta charset="utf-8">\n<meta name'
'="description" content="{}">\n<title>{}</title>\n'
'</head>\n<body>').format(desc, html_title))
# Special case: Martial God Asura
if "mga-index" in url:
# Get chapters in this volume
match_obj = re.search('\((\d+)-(\d+)\)', elem.text)
ch_begin, ch_end = match_obj.groups()
# Then just loop over chapter URLs
for ch_num in range(int(ch_begin), int(ch_end) + 1):
time.sleep(delay) # Slow down a bit so we don't get banned
ch_url = url + "/mga-chapter-{}".format(ch_num)
if debug:
print "DEBUG: Fetching chapter URL: {}".format(ch_url)
process_chapter_page(ch_url, ch_num, out, debug)
# Close out html
out.write("\n\n</body>\n</html>\n")
continue
# Now request each chapter and extract the content
# NOTE: This could be parallelized, but we don't want to get banned!
# A scraper might get banned anyway...
ch_num = 0
for ch_url in elem.find_all_next(True):
# If it's a horizontal rule or a strong, there's a new book
if ch_url.name in ['hr', 'strong'] and ch_num > 0:
print "Found end of Book {}...".format(booknum)
break
# If it's something other than an anchor, skip it
elif ch_url.name != 'a':
continue
# If there is no link target, skip it
elif ch_url.get('href') is None:
continue
time.sleep(delay) # Slow down a bit so we don't get banned
actual_ch_url = ch_url.get('href')
# Manual override for ATG link mistakes (e.g. Ch 128)
if ".com/atg-ch" in actual_ch_url:
if debug:
print "DEBUG: Found link error:"
print "DEBUG: {}".format(actual_ch_url)
print "DEBUG: Link replaced"
actual_ch_url = actual_ch_url.replace(".com/atg-ch", ".com/atg-index/atg-ch")
if debug:
print "DEBUG: Fetching chapter URL:"
print "DEBUG: {}".format(actual_ch_url)
ch_num += 1
process_chapter_page(actual_ch_url, ch_num, out, debug)
# Close out html
out.write("\n\n</body>\n</html>\n")
# Optionally run pandoc
if not skip_epub:
run_pandoc_on(fnames)
def main():
''' Take arguments and run scraper '''
import argparse
parser = argparse.ArgumentParser(description='Wuxiaworld Scraper')
parser.add_argument('url', help='Index page of story to scrape',
default='http://www.wuxiaworld.com/cdindex-html')
parser.add_argument('--delay', default='1',
help=('Delay between scraping chapters (don\'t wanna '
'get banned!)'))
parser.add_argument('--books', nargs='+', type=int, default=None,
help='The books to download (defaults to all)')
parser.add_argument('--no-epub', action='store_true',
help=('Automatically run pandoc to convert to epub. '
'(Requires pandoc on path)'))
parser.add_argument('-v', '--verbose', action='store_true',
help='Adds debugging statements to output')
args = parser.parse_args()
if args.verbose:
print "DEBUG: args passed to scraper:"
print "Index URL: {}".format(args.url)
print "Books: {}".format(str(args.books))
print "Delay: {}".format(str(args.delay))
print "No EPUB flag {}".format(str(args.no_epub))
scrape(args.url, args.books, float(args.delay), args.no_epub, args.verbose)
if __name__ == "__main__":
main()