BeautifulSoup คืออะไร?
BeautifulSoup เป็นไลบรารีภาษา Python สำหรับ แปลง (Parse) และ ดึงข้อมูล (Extract) จาก HTML และ XML documents
มันออกแบบมาให้รองรับเอกสารที่มีโครงสร้างผิดพลาด (Malformed HTML) ได้อย่างยืดหยุ่น
นอกจากนี้ยังสามารถค้นหาและกรองข้อมูลตาม tag, attribute, class name, id หรือแม้กระทั่งข้อความภายในได้อย่างง่ายดาย
จุดเด่นของ BeautifulSoup
- ใช้งานง่าย อ่านโค้ดแล้วเข้าใจได้ทันที
- รองรับ HTML ที่มีโครงสร้างผิดพลาด (ซึ่งเกิดบ่อยมากในเว็บจริง)
- ค้นหา tag หรือ element ได้หลากหลายวิธี เช่น find(), find_all(), select()
- ใช้ร่วมกับ requests ได้ดี สำหรับ web scraping
- มี parser หลายแบบให้เลือก: html.parser, lxml, html5lib
โค้ด: เลือกทั้งหมด
from bs4 import BeautifulSoup
html = """
<html>
<body>
<h1>ข่าวเด่น</h1>
<p class="summary">เนื้อหาสำคัญของข่าว...</p>
</body>
</html>
"""
soup = BeautifulSoup(html, 'html.parser')
print(soup.h1.text)
print(soup.find('p', class_='summary').text)
โค้ด: เลือกทั้งหมด
C:\Users\administator\Desktop> python .\test_bs.py
ข่าวเด่น
เนื้อหาสำคัญของข่าว...
- html.parser - Built-in ของ Python, ไม่ต้องติดตั้งเพิ่ม
- lxml - เร็วมาก, รองรับ XPath
- html5lib - แม่นยำสูง, รองรับ HTML5 เต็มรูปแบบ
โค้ด: เลือกทั้งหมด
import requests
from bs4 import BeautifulSoup
url = "https://www.mindphp.com/forums/viewforum.php?f=144"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
โค้ด: เลือกทั้งหมด
C:\Users\administator\Desktop> python .\test_bs.py
None
https://www.mindphp.com
#start_here
#
./memberlist.php?sid=f4344a86c131b41ff4c9eb506fd242d1
./memberlist.php?mode=team&sid=f4344a86c131b41ff4c9eb506fd242d1
/forums/app.php/help/faq?sid=f4344a86c131b41ff4c9eb506fd242d1
https://www.mindphp.com/forums/m_tools_dowry/index?sid=f4344a86c131b41ff4c9eb506fd242d1
./ucp.php?mode=login&redirect=viewforum.php%3Ff%3D144&sid=f4344a86c131b41ff4c9eb506fd242d1
./ucp.php?mode=register&sid=f4344a86c131b41ff4c9eb506fd242d1
https://www.mindphp.com
./index.php?sid=f4344a86c131b41ff4c9eb506fd242d1
./viewforum.php?f=23&sid=f4344a86c131b41ff4c9eb506fd242d1
./viewforum.php?f=29&sid=f4344a86c131b41ff4c9eb506fd242d1
./viewforum.php?f=144&sid=f4344a86c131b41ff4c9eb506fd242d1
.........................
- ทำงานช้ากว่า lxml ในการประมวลผลจำนวนมาก
- ไม่รองรับ XPath โดยตรง (ต้องใช้ lxml หากต้องการ XPath)
- ไม่เหมาะกับงาน JavaScript-rendered page (เช่น React, Vue) — ต้องใช้ Selenium หรือ Playwright แทน
- lxml - เร็ว รองรับ XPath
- html5lib - รองรับ HTML5 อย่างละเอียด
- parsel - ใช้ CSS Selector หรือ XPath ได้
- selectolax - เร็ว เบา เหมาะกับ scraping ขนาดใหญ่
BeautifulSoup เป็นไลบรารีที่เหมาะสำหรับผู้ที่ต้องการเรียนรู้ Web Scraping ด้วย Python มันใช้งานง่าย เหมาะกับโปรเจกต์เล็กถึงกลาง รองรับ HTML ที่ไม่สมบูรณ์ได้ดี ถึงแม้จะมีข้อจำกัดในด้าน performance หรือ XPath support แต่ก็ยังเป็นตัวเลือกอันดับต้น ๆ สำหรับคนที่ต้องการ "เริ่มต้นขุดข้อมูลจากเว็บ" อย่างมีประสิทธิภาพ หากสนใจเพิ่มเติมสามารถอ่านได้ที่ แนะนำโมดูล BeautifulSoup คืออะไร ใช้ทำอะไร? หรือ บทเรียน Python
อ้างอิง