2️⃣ Nếu train AI để hiểu cấu trúc trang web → GIỮ HTML NHƯNG CHUẨN HÓA
Nếu bạn muốn train mô hình để hiểu bố cục trang web, SEO, chatbot xử lý HTML, thì không nên bỏ hết HTML.
🔥 Thay vào đó, chỉ giữ lại các thẻ quan trọng:
def simplify_html(html_content): soup = BeautifulSoup(html_content, "html.parser") # Chỉ giữ lại các thẻ quan trọng allowed_tags = {"h1", "h2", "h3", "p", "ul", "ol", "li", "a", "strong", "em"} for tag in soup.find_all(): if tag.name not in allowed_tags: tag.unwrap() # Gỡ bỏ thẻ nhưng giữ nội dung bên trong return str(soup)
💡 Ví dụ Input:
<pre class="wp-block-syntaxhighlighter-code"><div><h1>Tiêu đề</h1><p>Đây là <span>nội dung</span> quan trọng.</p></div><br></pre>
💡 Kết quả Output:
<pre class="wp-block-syntaxhighlighter-code"><h1>Tiêu đề</h1><p>Đây là nội dung quan trọng.</p><br></pre>
✅ Ưu điểm:
Giữ nguyên cấu trúc quan trọng (h1, p, li…).
Không có thẻ CSS, script gây nhiễu.
Dễ train mô hình hiểu trang web.
3️⃣ Nếu train AI để sinh HTML từ text → GIỮ CẤU TRÚC NHƯNG DỌN DẸP
Nếu bạn muốn AI tạo HTML đẹp từ văn bản, thì giữ lại cấu trúc nhưng làm sạch các phần thừa.
🔥 Dọn dẹp mã HTML trước khi train:
<pre class="wp-block-syntaxhighlighter-code">import htmlmin<br><br>def clean_and_minify_html(html_content):<br> # Xóa các thẻ script, style, inline CSS<br> soup = BeautifulSoup(html_content, "html.parser")<br> for tag in soup(["script", "style"]):<br> tag.decompose()<br> <br> # Nén HTML để gọn hơn<br> return htmlmin.minify(str(soup), remove_empty_space=True)<br><br>html_example = "<html><body><h1>Tiêu đề</h1><script>alert('X');</script><p>Nội dung.</p></body></html>"<br>clean_html = clean_and_minify_html(html_example)<br>print(clean_html)<br></pre>
This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Strictly Necessary Cookies
Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.
If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.