forked from yidao620c/python3-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_cookbook.py
More file actions
175 lines (160 loc) · 6.18 KB
/
fetch_cookbook.py
File metadata and controls
175 lines (160 loc) · 6.18 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Seaky
# @Date: 2019/6/19 14:40
# pip install requests beautifulsoup4
import json
import re
from copy import deepcopy
from pathlib import Path
import requests
from bs4 import BeautifulSoup
TEMPLATE = {
"cells": [],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.1"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": True,
"sideBar": True,
"skip_h1_title": True,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": False,
"toc_position": {},
"toc_section_display": True,
"toc_window_display": True
}
},
"nbformat": 4,
"nbformat_minor": 2
}
class Chapter:
def __init__(self, chapter_address):
self.chapter_address = chapter_address
self.path = re.sub('/[^/]+?$', '/', chapter_address)
self.ss = requests.session()
def fetch(self, url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}
print(url)
raw = self.ss.get(url, headers=headers).content
m = re.search('charset=\W*(?P<charset>\w+)', raw[:200].decode(errors='ignore'))
charset = m.groupdict().get('charset', 'utf-8')
if charset == 'gb2312':
charset = 'cp936'
return raw.decode(encoding=charset)
def fetch_list(self):
content = self.fetch(self.chapter_address)
soup = BeautifulSoup(content, 'html.parser')
self.chapter_title = soup.find('h1').text.replace('¶', '')
self.chapter_desc = soup.find('p').text
self.sections = []
for x in soup.find_all('a', class_='reference internal', href=re.compile('/p\d+_')):
if x['href'] not in self.sections:
self.sections.append(x['href'])
def fetch_sections(self, sep=False):
cells = [{
"cell_type": "markdown",
"metadata": {},
"source": ['# {}\n {}'.format(self.chapter_title, self.chapter_desc)]
}]
dpath = Path('ipynb')
dpath.mkdir(exist_ok=True)
for href in self.sections[:]:
_cells = self.fetch_content(self.path + href)
if sep:
_dpath = dpath / self.chapter_title
_dpath.mkdir(exist_ok=True)
TEMPLATE['cells'] = _cells
*_, section_name = href.split('/')
open(str(_dpath / '{}.ipynb'.format(section_name.split('.')[0])), 'w').write(json.dumps(TEMPLATE, indent=2))
cells.extend(_cells)
TEMPLATE['cells'] = cells
open(str(dpath / '{}.ipynb'.format(self.chapter_title)), 'w').write(json.dumps(TEMPLATE, indent=2))
def fetch_content(self, url):
content = self.fetch(url)
soup = BeautifulSoup(content, 'html.parser')
cell_markdown = {
"cell_type": "markdown",
"metadata": {},
"source": []
}
cell_code = {
"cell_type": "code",
"execution_count": None,
"metadata": {},
"outputs": [],
"source": []
}
cells = []
p_header = re.compile('^h(?P<level>\d)$')
for tag in [x for x in soup.descendants if x.name]:
if p_header.search(tag.name):
cell = deepcopy(cell_markdown)
cell['source'].append(
'{} {}\n'.format('#' * (int(p_header.search(tag.name).group('level')) + 1), tag.text))
cells.append(cell)
elif tag.name == 'p':
if 'Copyright' in tag.text:
continue
cell = deepcopy(cell_markdown)
cell['source'].append(tag.text)
cells.append(cell)
elif tag.name == 'pre':
if '>>>' not in tag.text:
# code
source = [re.sub('(^\n*|\n*$)', '', tag.text)]
else:
# idle
source = []
for line in tag.text.split('\n'):
if re.search('^(>|\.){3}', line):
if re.search('^(>|\.){3}\s*$', line):
continue
source.append(re.sub('^(>|\.){3} ', '', line))
else:
if source:
cell = deepcopy(cell_code)
cell['source'].append(re.sub('(^\n*|\n*$)', '', '\n'.join(source)))
cells.append(cell)
source = []
else:
continue
if source:
cell = deepcopy(cell_code)
cell['source'].append('\n'.join(source))
cells.append(cell)
for cell in cells:
for i, text in enumerate(cell['source']):
cell['source'][i] = text.replace('¶', '')
return cells
def fetch_all(sep=False):
content = requests.get('https://python3-cookbook.readthedocs.io/zh_CN/latest/').content
soup = BeautifulSoup(content)
for x in soup.find_all('a', class_='reference internal', href=re.compile('chapters/p\d+'))[2:15]:
ch = Chapter('https://python3-cookbook.readthedocs.io/zh_CN/latest/' + x['href'])
ch.fetch_list()
ch.fetch_sections(sep=sep)
if __name__ == '__main__':
# ch = Chapter('https://python3-cookbook.readthedocs.io/zh_CN/latest/chapters/p01_data_structures_algorithms.html')
# ch.fetch_list()
# ch.fetch_sections()
fetch_all(sep=True)