Strip HTML Tags
strip_html · text · text
2026-09-23
กำลังประมวลผล…
strip_html · text · text
2026-09-23
ข้อมูลที่ดึงมาจากเว็บหรือระบบ CMS มักมีแท็ก HTML ติดมาในคอลัมน์คำอธิบาย การลบด้วยการค้นหาเครื่องหมาย < และ > เองมักพลาดกับ entity อย่าง & และเผลอเอาโค้ดใน <script> มาด้วย เทคนิคนี้อ่าน HTML จริงแล้วคืนเฉพาะข้อความ
a < b — ตรวจ Preview ก่อนเสมอ<script> และ <style> ทั้งก้อน<p>, <div>, <li>, <br> กลายเป็นการขึ้นบรรทัดใหม่ เพื่อไม่ให้ข้อความติดกันเป็นพืด& เป็น &| Parameter | Type | Default |
|---|---|---|
columns | string[] | — |
import html
import json
import re
BLOCKS = r'p|div|li|tr|br|h1|h2|h3|section|article'
def strip_html(value):
if not isinstance(value, str):
return value
text = re.sub(r'<(script|style)\b[\s\S]*?</\1>', '', value, flags=re.IGNORECASE)
text = re.sub(rf'</?({BLOCKS})\b[^>]*>', '\n', text, flags=re.IGNORECASE)
text = re.sub(r'<[^>]*>', '', text)
text = html.unescape(text)
return re.sub(r'\n{2,}', '\n', text).strip()
values = ['<b>ไทย</b> & Café<script>alert(1)</script>', '<p>a</p><p>b</p>', None]
print(json.dumps([strip_html(v) for v in values], ensure_ascii=False))
คอลัมน์ description จากระบบร้านค้ามีแท็ก <p> และ ปนอยู่ รัน strip_html แล้วตามด้วย remove_line_breaks ถ้าจะ export เป็น CSV และ collapse_spaces เพื่อเก็บช่องว่างซ้อน จากนั้นตรวจความยาวข้อความสูงสุดในหน้า Dataset ว่าลดลงตามที่คาด
ใช้ remove_line_breaks ต่อเมื่อจะส่งออกเป็นไฟล์ตาราง ใช้ collapse_spaces เพื่อจัดช่องว่าง และใช้ fix_mojibake ถ้าข้อความที่ได้ยังอ่านไม่ออก