ปัญหา
ต้องการดึงตาราง HTML จากเว็บเพจ
บทนำ
อินเทอร์เน็ต/เว็บเป็นแหล่งข้อมูลสำคัญ ใช้ HTTP ดึงข้อมูล Python มี standard library แต่ requests module ทำให้ง่ายกว่า บทความนี้แสดงวิธี parse HTML หาตารางฝังอยู่ในหน้าเว็บ
ขั้นตอนการทำงาน
1. ติดตั้งแพ็กเกจ: requests, pandas, beautifulsoup4, tabulate
2. ดึงหน้าเว็บตัวอย่าง
import requests
import pandas as pd
from tabulate import tabulate
site_url = "https://www.tutorialspoint.com/python/python_basic_operators.htm"
response = requests.get(site_url)
print(f"Response status: {response.status_code}") # 200 = success
3. ตรวจสอบ Header และเนื้อหา
print(response.request.headers)
print(response.headers)
print(response.text[:100]) # 100 ตัวอักษรแรก
4. Parse HTML ด้วย BeautifulSoup
from bs4 import BeautifulSoup
tutorialpoints_page = BeautifulSoup(response.text, 'html.parser')
print(tutorialpoints_page.title)
print(tutorialpoints_page.title.string)
5. หาตาราง: ค้นหา heading tags (h2-h6) แล้วหา table ถัดไป
tags = tutorialpoints_page.find(lambda elm: elm.name in ["h2","h3","h4","h5","h6"])
for sibling in tags.find_next_siblings():
if sibling.name == "table":
my_table = sibling
df = pd.read_html(str(my_table))
print(tabulate(df[0], headers='keys', tablefmt='psql'))
6. โค้ดรวมทั้งหมด
import requests
import pandas as pd
from bs4 import BeautifulSoup
from tabulate import tabulate
site_url = "https://www.tutorialspoint.com/python/python_basic_operators.htm"
response = requests.get(site_url)
print(f"Response: {response.status_code}")
tutorialpoints_page = BeautifulSoup(response.text, 'html.parser')
print(f"Title: {tutorialpoints_page.title.string}")
tags = tutorialpoints_page.find(lambda elm: elm.name in ["h2","h3","h4","h5","h6"])
for sibling in tags.find_next_siblings():
if sibling.name == "table":
my_table = sibling
df = pd.read_html(str(my_table))
print(tabulate(df[0], headers='keys', tablefmt='psql'))
ผลลัพธ์
จะได้ตารางต่างๆ จากหน้าเว็บ เช่น ตาราง Arithmetic Operators, Comparison Operators, Assignment Operators, Bitwise Operators, Logical Operators, Membership Operators, Identity Operators, Operator Precedence พร้อมคำอธิบายและตัวอย่าง
สรุป
- ใช้
requestsดึง HTML - ใช้
BeautifulSoupparse DOM - หา heading tags แล้วหา
tablesibling ถัดไป - ใช้
pd.read_html()แปลง HTML table → DataFrame - ใช้
tabulateพิมพ์สวยใน console