/
fetch_vangohan.py
238 lines (197 loc) · 7.97 KB
/
fetch_vangohan.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
import base64
import logging
import os
import pathlib
from io import BytesIO
from typing import List
import chromedriver_autoinstaller
import httpx
import markdown
from PIL import Image
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
# This template is based on https://gist.github.com/Fedik/674f4148439698a6681032b3bec370b3
TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="referrer" content="no-referrer" />
<meta name="referrer" content="unsafe-url" />
<meta name="referrer" content="origin" />
<meta name="referrer" content="no-referrer-when-downgrade" />
<meta name="referrer" content="origin-when-cross-origin" />
<title>Page Title</title>
<link href="bootstrap.min.css" rel="stylesheet">
<style>
body {
font-family: Helvetica,Arial,sans-serif;
}
code, pre {
font-family: monospace;
}
</style>
</head>
<body>
<div class="container mt-3">
{{content}}
</div>
</body>
</html>
"""
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logging.getLogger("WDM").setLevel(logging.WARNING)
class VangohanScraper:
VANGOHAN_URL = "https://light-nyala-71c.notion.site/VanGohan-Instructions-0290b31c1baf4eeab79613508adeba38"
def __init__(self):
chromedriver_autoinstaller.install()
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-gpu")
self.driver = webdriver.Chrome(options=chrome_options,)
def __del__(self):
self.driver.quit()
def save_menu_image(self):
logger.info("fetching menu image")
self.driver.get(self.VANGOHAN_URL)
menu = WebDriverWait(self.driver, 20).until(
EC.visibility_of_element_located(
(
By.XPATH,
'//div[contains(text(), " Menu")]/ancestor::a',
)
)
)
menu.click() # open menu page
img = WebDriverWait(self.driver, 20).until(
EC.visibility_of_element_located(
(By.XPATH, '//div[@class="notion-cursor-default"]//img')
)
)
src = img.get_attribute("src")
r = httpx.get(src)
i = Image.open(BytesIO(r.content))
i.save("menu.png")
def fetch_recipes(self) -> List[str]:
logger.info("fetching recipes")
self.driver.get(self.VANGOHAN_URL)
articles = WebDriverWait(self.driver, 20).until(
EC.visibility_of_all_elements_located(
(
By.XPATH,
'//div[@class="notion-selectable notion-page-block notion-collection-item"]/a',
)
)
)
urls = [article.get_attribute("href") for article in articles]
recipes = []
IGNORE_URL_PATTERNS = ["-Menu-", "Welcome-to-VanGohan"]
for url in urls:
if any(pat in url for pat in IGNORE_URL_PATTERNS):
continue
self.driver.get(url)
content_path = '//div[@class="notion-page-content"]'
content = WebDriverWait(self.driver, 20).until(
EC.visibility_of_element_located((By.XPATH, content_path))
)
recipes.append(content.get_attribute("innerText"))
return recipes
def save_recipes(self, recipes: List[str], fname: str, lang: str = "ja"):
logger.info("parsing html")
en_title1 = "Things you need to prepare"
en_title2 = "Instructions"
ja_title1 = "ご自宅でご用意いただくもの"
ja_title2 = "インストラクション"
tips = "Tips"
en_flag = False
with open(fname, "w") as f:
for recipe in recipes:
rows = recipe.split("\n")
title_row = 1 if lang == "ja" else 0
f.write(f"## {rows[title_row]}\n") # title
instruction_flag = False
for row in rows[2:]:
if not row:
continue
elif row == ja_title1 or (is_title2 := row.startswith(ja_title2)):
en_flag = False
if lang == "ja":
if is_title2:
instruction_flag = True
f.write("\n#### ")
elif row == en_title1 or (is_title2 := row.startswith(en_title2)):
en_flag = True
if lang == "en":
if is_title2:
instruction_flag = True
f.write("\n#### ")
elif row == tips:
instruction_flag = False
f.write("\n#### ")
else:
if not en_flag and lang == "ja":
prefix = "1. " if instruction_flag else "- "
f.write(prefix)
elif en_flag and lang == "en":
prefix = "1. " if instruction_flag else "- "
f.write(prefix)
if lang == "ja" and en_flag:
continue
elif lang == "en" and not en_flag:
continue
f.write(f"{row}\n")
f.write("\n\n")
f.write("<img src='./menu.png' height='600'>\n")
def html2pdf2(self, input_fname: str, output_fname: str):
logger.info("Saving PDF")
path = os.path.abspath(input_fname)
url = pathlib.Path(path).as_uri()
self.driver.get(url)
print_options = {
"landscape": False,
"displayHeaderFooter": False,
"printBackground": True,
"preferCSSPageSize": True,
"pageSize": "Letter",
}
result = self._send_devtools(self.driver, "Page.printToPDF", print_options)
with open(output_fname, "wb") as f:
f.write(base64.b64decode(result["data"]))
# From https://gist.github.com/bloodwithmilk25/3e05719829ae875319485bc52fcd294e#file-pdf_generator_simple_version-py
@staticmethod
def _send_devtools(driver, cmd, params):
"""
Works only with chromedriver.
Method uses cromedriver's api to pass various commands to it.
"""
import json
resource = f"/session/{driver.session_id}/chromium/send_command_and_get_result"
url = driver.command_executor._url + resource
body = json.dumps({"cmd": cmd, "params": params})
response = driver.command_executor._request("POST", url, body)
return response.get("value")
def md2html(input_fname: str, output_fname: str):
with open(input_fname, "r") as f:
md = f.read()
extensions = ["extra", "smarty"]
html = markdown.markdown(md, extensions=extensions, output_format="html5")
doc = TEMPLATE.replace("{{content}}", html)
with open(output_fname, "w") as fw:
fw.write(doc)
if __name__ == "__main__":
vs = VangohanScraper()
vs.save_menu_image()
recipes = vs.fetch_recipes()
vs.save_recipes(recipes, "vangohan.md", lang="ja")
md2html("vangohan.md", "vangohan.html")
pathlib.Path("results").mkdir(parents=True, exist_ok=True)
vs.html2pdf2("vangohan.html", pathlib.Path("results", "vangohan.pdf"))
vs.save_recipes(recipes, "vangohan-en.md", lang="en")
md2html("vangohan-en.md", "vangohan-en.html")
vs.html2pdf2("vangohan-en.html", pathlib.Path("results", "vangohan_en.pdf"))