Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีลบ Empty Tags ด้วย BeautifulSoup ใน Python

BeautifulSoup เป็นไลบรารี Python ที่ดึงข้อมูลจากไฟล์ HTML และ XML ด้วย BeautifulSoup เราสามารถลบ Empty Tags ที่อยู่ในเอกสาร HTML หรือ XML และแปลงข้อมูลให้อ่านง่ายขึ้นได้

ก่อนอื่น เราจะติดตั้งไลบรารี BeautifulSoup ใน Environment ท้องถิ่นด้วยคำสั่ง: pip install beautifulsoup4

ตัวอย่าง

# Import the BeautifulSoup library
from bs4 import BeautifulSoup

# Get the html document
html_object = """

Python is an interpreted, high-level and general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant indentation.

""" # Let us create the soup for the given html document soup = BeautifulSoup(html_object, "lxml") # Iterate over each line of the document and extract the data for x in soup.find_all(): if len(x.get_text(strip=True)) == 0: x.extract() print(soup)

ผลลัพธ์

การรันโค้ดข้างต้นจะสร้างผลลัพธ์และแปลงเอกสาร HTML ให้เป็นโค้ดที่อ่านง่ายโดยการลบ Empty Tags

Python is an interpreted, high-level and general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant indentation.