บทนำ
BeautifulSoup เป็นไลบรารีของ Python ภายนอก (third-party) ที่ใช้สำหรับแยกวิเคราะห์ (parse) ข้อมูลจากหน้าเว็บ มันช่วยให้ทำ Web Scraping ได้ง่ายขึ้น ซึ่งเป็นกระบวนการดึงข้อมูล ใช้งาน และจัดการข้อมูลจากแหล่งต่างๆ
Web Scraping ยังสามารถนำไปใช้สำหรับการวิจัย ทำความเข้าใจ/เปรียบเทียบแนวโน้มตลาด ติดตาม SEO และอื่นๆ อีกมากมาย
การติดตั้ง
รันคำสั่งด้านล่างเพื่อติดตั้ง BeautifulSoup บน Windows:
pip install beautifulsoup4
ตัวอย่างโค้ด
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
import urllib
url = 'https://en.wikipedia.org/wiki/Algorithm'
html = urlopen(url).read()
print("Reading the webpage...")
soup = BeautifulSoup(html, features="html.parser")
print("Parsing the webpage...")
# ลบแท็ก script และ style ออก
for script in soup(["script", "style"]):
script.extract()
print("Extracting text from the webpage...")
text = soup.get_text()
print("Data cleaning...")
# ทำความสะอาดข้อความ: ลบบรรทัดว่างและช่องว่างเกิน
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = '\n'.join(chunk for chunk in chunks if chunk)
text = str(text)
print(text)ผลลัพธ์ตัวอย่าง
Reading the webpage... Parsing the webpage... Extracting text from the webpage... Data cleaning... Recursive C implementation of Euclid's algorithm from the above flowchart Recursion A recursive algorithm is one that invokes (makes reference to) itself repeatedly until a certain condition (also known as termination condition) matches, which is a method common to functional programming…. ….. Developers Statistics Cookie statement
คำอธิบายขั้นตอน
นำเข้าแพ็กเกจที่จำเป็นและตั้งชื่ออุปมา (alias)
กำหนด URL ของเว็บไซต์เป้าหมาย
- เปิด URL และลบแท็ก 'script' รวมถึงแท็ก HTML ที่ไม่เกี่ยวข้องอื่นๆ
ใช้ฟังก์ชัน 'get_text' เพื่อดึงข้อความจากข้อมูลเว็บเพจ
กำจัดช่องว่างเกินและคำที่ไม่ถูกต้อง
แสดงข้อความที่ผ่านการทำความสะอาดแล้วบนคอนโซล