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
|
#!/usr/bin/env python3
import os
import sys
import urllib.parse
import urllib.robotparser
import html.parser
import json
import requests
import mimetypes
from collections import deque
class LinkExtractor(html.parser.HTMLParser):
def __init__(self):
super().__init__()
self.links = []
self.images = []
self.scripts = []
self.styles = []
self.text_parts = []
self.title = ''
self.meta = {}
self.in_title = False
def handle_starttag(self, tag, attrs):
if tag == 'a':
for attr, value in attrs:
if attr == 'href':
self.links.append(value)
elif tag == 'img':
for attr, value in attrs:
if attr == 'src':
self.images.append(value)
elif tag == 'script':
for attr, value in attrs:
if attr == 'src':
self.scripts.append(value)
elif tag == 'link':
rel = None
href = None
for attr, value in attrs:
if attr == 'rel':
rel = value
elif attr == 'href':
href = value
if rel in ['stylesheet', 'icon'] and href:
self.styles.append(href)
elif tag == 'title':
self.in_title = True
elif tag == 'meta':
name = None
content = None
for attr, value in attrs:
if attr == 'name' or attr == 'property':
name = value
elif attr == 'content':
content = value
if name and content:
self.meta[name] = content
def handle_endtag(self, tag):
if tag == 'title':
self.in_title = False
def handle_data(self, data):
if self.in_title:
self.title += data
else:
self.text_parts.append(data.strip())
def download_asset(url, base_path, timeout=10):
try:
resp = requests.get(url, timeout=timeout)
if resp.status_code == 200:
content_type = resp.headers.get('content-type', '')
ext = mimetypes.guess_extension(content_type) or '.bin'
filename = os.path.basename(urllib.parse.urlparse(url).path)
if not filename:
filename = 'asset' + ext
elif not os.path.splitext(filename)[1]:
filename += ext
filepath = os.path.join(base_path, filename)
os.makedirs(os.path.dirname(filepath), exist_ok=True)
with open(filepath, 'wb') as f:
f.write(resp.content)
return filepath
except Exception as e:
print(f"Error downloading {url}: {e}")
return None
def main():
base_url = 'https://nixtamal.toast.al'
# Check robots.txt
rp = urllib.robotparser.RobotFileParser()
rp.set_url(base_url + '/robots.txt')
try:
rp.read()
if not rp.can_fetch('*', base_url + '/'):
print("Crawling not allowed by robots.txt")
sys.exit(1)
except:
print("Could not read robots.txt, proceeding assuming allowed")
# Create directories
os.makedirs('docs/archive', exist_ok=True)
os.makedirs('docs/archive/assets', exist_ok=True)
visited = set()
queue = deque([base_url])
pages_data = {}
while queue:
url = queue.popleft()
if url in visited:
continue
visited.add(url)
print(f"Crawling: {url}")
try:
resp = requests.get(url, timeout=10)
if resp.status_code != 200:
print(f"Skipping {url} with status {resp.status_code}")
continue
content = resp.text
parser = LinkExtractor()
parser.feed(content)
# Make links absolute
abs_links = []
for link in parser.links:
abs_link = urllib.parse.urljoin(url, link)
if abs_link.startswith(base_url):
abs_links.append(abs_link)
if abs_link not in visited and abs_link not in queue:
queue.append(abs_link)
# Download assets
assets = []
for img in parser.images:
img_url = urllib.parse.urljoin(url, img)
if img_url.startswith(base_url):
path = download_asset(img_url, 'docs/archive/assets')
if path:
assets.append({'type': 'image', 'url': img_url, 'local_path': path})
for script in parser.scripts:
script_url = urllib.parse.urljoin(url, script)
if script_url.startswith(base_url):
path = download_asset(script_url, 'docs/archive/assets')
if path:
assets.append({'type': 'script', 'url': script_url, 'local_path': path})
for style in parser.styles:
style_url = urllib.parse.urljoin(url, style)
if style_url.startswith(base_url):
path = download_asset(style_url, 'docs/archive/assets')
if path:
assets.append({'type': 'style', 'url': style_url, 'local_path': path})
# Save page
path = urllib.parse.urlparse(url).path
if not path or path == '/':
filename = 'index.html'
else:
filename = path.strip('/').replace('/', '_') + '.html'
filepath = os.path.join('docs/archive', filename)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
# Collect data
pages_data[url] = {
'title': parser.title,
'meta': parser.meta,
'text': ' '.join(parser.text_parts),
'links': abs_links,
'assets': assets,
'local_file': filepath
}
except Exception as e:
print(f"Error crawling {url}: {e}")
# Save structure
with open('docs/archive/structure.json', 'w', encoding='utf-8') as f:
json.dump(pages_data, f, indent=2, ensure_ascii=False)
print("Crawling complete. Data saved to docs/archive/")
if __name__ == '__main__':
main()
|