This repository has been archived by the owner on Nov 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 175
/
gitbook.py
executable file
·279 lines (236 loc) · 9.35 KB
/
gitbook.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
import html
import requests
import asyncio
import aiohttp
import weasyprint
import datetime
import os
import re
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
from lxml import etree
import sys
async def request(url, headers, timeout=None):
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, timeout=timeout) as resp:
return await resp.text()
def local_ua_stylesheets(self):
return [weasyprint.CSS('./html5_ua.css')]
def load_gitbook_css():
with open('gitbook.css', 'r') as f:
return f.read()
def get_level_class(num):
'''
return 'level'+num
'''
return 'level' + str(num)
class HtmlGenerator():
def __init__(self, base_url):
self.html_start = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
"""
self.title_ele = ""
self.meta_list = []
self.body = ""
self.html_end = """
</body>
</html>
"""
self.base_url = base_url
def add_meta_data(self, key, value):
meta_string = "<meta name={key} content={value}>".format_map({
'key': key,
'value': value
})
self.meta_list.append(meta_string)
def add_body(self, body):
self.body = body
def srcrepl(self, match):
"Return the file contents with paths replaced"
absolutePath = self.base_url
return "<" + match.group(1) + match.group(2) + "=" + "\"" + absolutePath + match.group(3) + match.group(
4) + "\"" + ">"
def relative_to_absolute_path(self, origin_text):
p = re.compile(r"<(.*?)(src|href)=\"(?!http)(.*?)\"(.*?)>")
updated_text = p.sub(self.srcrepl, origin_text)
return updated_text
def output(self):
full_html = self.html_start + self.title_ele + "".join(self.meta_list) \
+ "<body>" + self.body + self.html_end
return self.relative_to_absolute_path(full_html)
class Gitbook2PDF():
def __init__(self, base_url, fname=None):
self.fname = fname
self.base_url = base_url
self.headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
}
self.content_list = []
self.heads = {'h1': 1, 'h2': 2, 'h3': 3, 'h4': 4, 'h5': 5, 'h6': 6}
self.meta_list = []
self.meta_list.append(
('generator', 'gitbook2pdf')
)
weasyprint.HTML._ua_stylesheets = local_ua_stylesheets
def run(self):
content_urls = self.collect_urls_and_metadata(self.base_url)
self.content_list = ["" for _ in range(len(content_urls))]
loop = asyncio.get_event_loop()
loop.run_until_complete(self.crawl_main_content(content_urls))
loop.close()
# main body
body = "".join(self.content_list)
# 使用HtmlGenerator类来生成HTML
html_g = HtmlGenerator(self.base_url)
html_g.add_body(body)
for key, value in self.meta_list:
html_g.add_meta_data(key, value)
html_text = html_g.output()
css_text = load_gitbook_css()
self.write_pdf(self.fname, html_text, css_text)
async def crawl_main_content(self, content_urls):
tasks = []
for index, urlobj in enumerate(content_urls):
if urlobj['url']:
tasks.append(self.gettext(index, urlobj['url'], urlobj['level'], urlobj['title']))
else:
tasks.append(self.getext_fake(index, urlobj['title'], urlobj['level']))
await asyncio.gather(*tasks)
print("crawl : all done!")
async def getext_fake(self, index, title, level):
await asyncio.sleep(0.01)
class_ = get_level_class(level)
string = "<h1 class='{class}'>{title}</h1>".format_map({
'class': class_,
'title': title
})
self.content_list[index] = string
async def gettext(self, index, url, level, title):
'''
return path's html
'''
print("crawling : ", url)
try:
metatext = await request(url, self.headers, timeout=10)
except Exception as e:
print("retrying : ", url)
metatext = await request(url, self.headers)
tree = etree.HTML(metatext)
try:
if tree.xpath('//section[@class="normal markdown-section"]'):
context = tree.xpath('//section[@class="normal markdown-section"]')[0]
elif tree.xpath('//section[@class="normal"]'):
context = tree.xpath('//section[@class="normal"]')[0]
if context.find('footer'):
context.remove(context.find('footer'))
for header in self.heads:
if context.xpath(header):
context.xpath(header)[0].attrib['class'] = get_level_class(level)
context.xpath(header)[0].text = title
break
text = etree.tostring(context).decode()
text = html.unescape(text)
print("done : ", url)
self.content_list[index] = text
except IndexError:
print('faild at : ', url, ' maybe content is empty?')
def write_pdf(self, fname, html_text, css_text):
tmphtml = weasyprint.HTML(string=html_text)
tmpcss = weasyprint.CSS(string=css_text)
fname = "./output/" + fname
htmlname = fname.replace('.pdf', '.html')
with open(htmlname, 'w', encoding='utf-8') as f:
f.write(html_text)
tmphtml.write_pdf(fname, stylesheets=[tmpcss])
def collect_urls_and_metadata(self, start_url):
text = requests.get(start_url, headers=self.headers).text
soup = BeautifulSoup(text, 'html.parser')
# 如果不提供输出文件名的话,抓取html标题为文件名
if not self.fname:
title_ele = soup.find('title')
if title_ele:
title = title_ele.text
if '·' in title:
title = title.split('·')[1]
if '|' in title:
title = title.split('|')[1]
title = title.replace(' ', '').replace('/', '-')
self.fname = title + '.pdf'
self.meta_list.append(
('title', self.fname.replace('.pdf', ''))
)
# get description meta data
comments_section = soup.find_all(class_='comments-section')
if comments_section:
description = comments_section[0].text.replace('\n', '').replace('\t', '')
self.meta_list.append(
('description', description)
)
# get author meta
author_meta = soup.find('meta', {'name': 'author'})
if author_meta:
author = author_meta.attrs['content']
else:
author = urlparse(self.base_url).netloc
self.meta_list.append(
('author', author)
)
# creation date and modification date : default now
# see : https://www.w3.org/TR/NOTE-datetime
now = datetime.datetime.utcnow().replace(microsecond=0).isoformat()
self.meta_list.append(('dcterms.created', now))
self.meta_list.append(('dcterms.modified', now))
lis = soup.find('ul', class_='summary').find_all('li')
found_urls = []
content_urls = []
for li in lis:
element_class = li.attrs.get('class')
if not element_class:
continue
if 'header' in element_class:
title = ' '.join(li.text.split())
data_level = li.attrs.get('data-level')
level = len(data_level.split('.')) if data_level else 1
content_urls.append({
'url': "",
'level': level,
'title': title
})
elif "chapter" in element_class:
data_level = li.attrs.get('data-level')
level = len(data_level.split('.'))
if 'data-path' in li.attrs:
data_path = li.attrs.get('data-path')
url = urljoin(start_url, data_path)
title = ' '.join(li.find('a').text.split())
if url not in found_urls:
content_urls.append(
{
'url': url,
'level': level,
'title': title
}
)
found_urls.append(url)
# 点击不了的链接
else:
# 一种获取方式 : http://self-publishing.ebookchain.org/
if li.find('span'):
title = ' '.join(li.find('span').text.split())
elif len(li.contents) == 1:
# 只有一个子节点,也就是文字
title = ' '.join(li.text.split())
content_urls.append({
'url': "",
'level': level,
'title': title
})
return content_urls
if __name__ == '__main__':
# Gitbook2PDF("http://self-publishing.ebookchain.org").run()
# Gitbook2PDF("https://feisky.xyz/kubernetes-handbook/").run()
url = sys.argv[1]
Gitbook2PDF(url).run()