BeautifulSoup เป็น Library Python ภายนอกสำหรับ Parse ข้อมูลจากหน้าเว็บ ใช้ใน Web Scraping (ดึงข้อมูล จัดการ วิเคราะห์จากแหล่งต่างๆ) ใช้ได้ทั้ง Research, Market Trends, SEO Monitoring ฯลฯ
ติดตั้ง BeautifulSoup บน Windows:
pip install beautifulsoup4
ตัวอย่าง
from bs4 import BeautifulSoup
import requests
url = "https://en.wikipedia.org/wiki/Algorithm"
req = requests.get(url)
soup = BeautifulSoup(req.text, "html.parser")
print("The href links are :")
for link in soup.find_all('a'):
print(link.get('href'))
ผลลัพธ์
The href links are : … https://stats.wikimedia.org/#/en.wikipedia.org https://foundation.wikimedia.org/wiki/Cookie_statement https://wikimediafoundation.org/ https://www.mediawiki.org/
คำอธิบาย
Import Packages ที่จำเป็น
กำหนด URL เว็บไซต์
เปิด URL และอ่านข้อมูล
ใช้ BeautifulSoup Parse HTML
ใช้
find_all('a')หา Tag Anchor ทั้งหมดดึง Attribute
hrefและพิมพ์