Web Scraping คือการดึงข้อมูลจากเว็บไซต์ แปลงข้อมูลไม่มีโครงสร้าง (unstructured) บนเว็บ ให้เป็นข้อมูลมีโครงสร้าง (structured)
เครื่องมือยอดนิยมใน Python 3
- urllib.request - Built-in (Python 3)
- Requests - HTTP library ที่ใช้งานง่ายที่สุด
- BeautifulSoup - HTML/XML parser
- lxml - High-performance parser
- Selenium - Browser automation (JavaScript rendering)
- MechanicalSoup - Stateful browser simulation
1. urllib.request (Built-in)
from urllib.request import urlopen
html = urlopen("https://www.tutorialspoint.com/")
print(html.read()[:500]) # แสดง 500 ตัวอักษรแรก
2. Requests (แนะนำสำหรับ HTTP)
pip install requests
import requests
resp = requests.get('https://www.tutorialspoint.com/')
print("Encoding:", resp.encoding)
print("Status:", resp.status_code)
print("Elapsed:", resp.elapsed)
print("URL:", resp.url)
print("History:", resp.history)
print("Content-Type:", resp.headers['Content-Type'])
ผลลัพธ์
Encoding: UTF-8
Status: 200
Elapsed: 0:00:00.205727
URL: https://www.tutorialspoint.com/
History: []
Content-Type: text/html; charset=UTF-8
3. BeautifulSoup (Parsing HTML)
pip install beautifulsoup4
from bs4 import BeautifulSoup
import requests
resp = requests.get("https://www.tutorialspoint.com/")
soup = BeautifulSoup(resp.text, 'html.parser')
# หา link ทั้งหมด
for link in soup.find_all('a'):
href = link.get('href')
if href:
print(href)
4. lxml (High Performance Parser)
pip install lxml
from lxml import etree
root = etree.Element('html')
etree.SubElement(root, 'head')
etree.SubElement(root, 'title')
etree.SubElement(root, 'body')
print(etree.tostring(root, pretty_print=True).decode('utf-8'))
ผลลัพธ์
5. Selenium (JavaScript-heavy Sites)
pip install selenium
# ต้องติดตั้ง WebDriver (ChromeDriver, GeckoDriver) แยกต่างหาก
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
service = Service('/path/to/chromedriver')
driver = webdriver.Chrome(service=service)
driver.get('https://www.tutorialspoint.com/')
print(driver.title)
driver.quit()

6. MechanicalSoup (Form Handling)
pip install MechanicalSoup
import mechanicalsoup
browser = mechanicalsoup.StatefulBrowser()
resp = browser.open("https://www.tutorialspoint.com/")
print("Response:", resp)
print("URL:", browser.get_url())
# ตามลิงก์และ submit form
browser.follow_link("forms")
print("New URL:", browser.get_url())
สรุปการเลือกใช้
| Tool | เหมาะสำหรับ | JavaScript | ความยาก |
|---|---|---|---|
| urllib | Simple GET, ไม่ต้องติดตั้ง | ไม่รองรับ | ต่ำ |
| Requests | HTTP ทุกประเภท, API | ไม่รองรับ | ต่ำ |
| BeautifulSoup | Parse HTML/XML | ไม่รองรับ | ต่ำ-ปานกลาง |
| lxml | Parse เร็ว, XML ซับซ้อน | ไม่รองรับ | ปานกลาง |
| Selenium | JS rendering, SPA, Login flow | รองรับ | สูง |
| MechanicalSoup | Form submit, Session, Cookie | ไม่รองรับ | ปานกลาง |
แนวทางปฏิบัติ: เริ่ม Requests + BeautifulSoup ก่อน ถ้าเว็บใช้ JS เยอะ纔用 Selenium