วันที่ 22 — Web Scraping
เรียนรู้การดึงข้อมูลจากเว็บไซต์ด้วย Python โดยใช้ requests และ BeautifulSoup4 เพื่อเก็บข้อมูลและนำไปใช้งานในรูปแบบต่างๆ

Python Web Scraping
Web Scraping คืออะไร (What is Web Scraping)
อินเทอร์เน็ตเต็มไปด้วยข้อมูลจำนวนมหาศาลที่สามารถนำมาใช้เพื่อวัตถุประสงค์ต่างๆ ได้ เพื่อเก็บรวบรวมข้อมูลเหล่านี้ เราจำเป็นต้องรู้วิธีดึงข้อมูล (scrape) จากเว็บไซต์
Web scraping คือกระบวนการดึงและเก็บรวบรวมข้อมูลจากเว็บไซต์ แล้วจัดเก็บไว้บนเครื่องภายในหรือในฐานข้อมูล
ในส่วนนี้ เราจะใช้ beautifulsoup และ requests package ในการดึงข้อมูล โดยใช้ beautifulsoup เวอร์ชัน 4
ในการเริ่มต้น scrape เว็บไซต์ คุณต้องมี requests, beautifulsoup4 และเว็บไซต์ที่ต้องการดึงข้อมูล
pip install requests
pip install beautifulsoup4ในการดึงข้อมูลจากเว็บไซต์ จำเป็นต้องมีความเข้าใจพื้นฐานเกี่ยวกับ HTML tags และ CSS selectors เราระบุเนื้อหาจากเว็บไซต์โดยใช้ HTML tags, classes หรือ/และ ids ลองนำเข้าโมดูล requests และ BeautifulSoup:
import requests
from bs4 import BeautifulSoupประกาศตัวแปร url สำหรับเว็บไซต์ที่เราจะดึงข้อมูล:
import requests
from bs4 import BeautifulSoup
url = 'https://archive.ics.uci.edu/ml/datasets.php'
# Lets use the requests get method to fetch the data from url
response = requests.get(url)
# lets check the status
status = response.status_code
print(status) # 200 means the fetching was successful200ใช้ beautifulSoup เพื่อ parse เนื้อหาจากหน้าเว็บ:
import requests
from bs4 import BeautifulSoup
url = 'https://archive.ics.uci.edu/ml/datasets.php'
response = requests.get(url)
content = response.content # we get all the content from the website
soup = BeautifulSoup(content, 'html.parser') # beautiful soup will give a chance to parse
print(soup.title) # <title>UCI Machine Learning Repository: Data Sets</title>
print(soup.title.get_text()) # UCI Machine Learning Repository: Data Sets
print(soup.body) # gives the whole page on the website
print(response.status_code)
tables = soup.find_all('table', {'cellpadding':'3'})
# We are targeting the table with cellpadding attribute with the value of 3
# We can select using id, class or HTML tag , for more information check the beautifulsoup doc
table = tables[0] # the result is a list, we are taking out data from it
for td in table.find('tr').find_all('td'):
print(td.text)ถ้ารันโค้ดนี้ จะเห็นว่าการดึงข้อมูลเสร็จไปครึ่งหนึ่งแล้ว คุณสามารถดำเนินการต่อเองได้เพราะเป็นส่วนหนึ่งของแบบฝึกหัดที่ 1 สำหรับข้อมูลเพิ่มเติม ดูได้ที่ beautifulsoup documentation: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#quick-start
💻 แบบฝึกหัด — วันที่ 22
- ดึงข้อมูลจากเว็บไซต์ต่อไปนี้และจัดเก็บข้อมูลเป็นไฟล์ json (url = 'http://www.bu.edu/president/boston-university-facts-stats/')
- ดึงตารางข้อมูลจาก URL นี้ (https://archive.ics.uci.edu/ml/datasets.php) และแปลงเป็นไฟล์ json
- ดึงข้อมูลตารางประธานาธิบดีและจัดเก็บเป็น json (https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States) ตารางนี้มีโครงสร้างที่ไม่ค่อยเป็นระเบียบ และการ scraping อาจใช้เวลานานมาก