「爬蟲」其實就是一個自動化程式,能模擬人類打開瀏覽器的動作,把網頁內容下載下來,並從中擷取需要的資料。
常見用途:
要注意:
html
... /html
的標籤title
、a
、div
)BeautifulSoup 是一個「HTML 解析器」。
它能把雜亂的 HTML 變成「樹狀結構」,讓你用簡單的方式找到想要的資料。
例如
from bs4 import BeautifulSoup
html = "<html><head><title>Python 爬蟲教學</title></head><body><p>Hello!</p></body></html>"
soup = BeautifulSoup(html, "html.parser")
print(soup.title.text) # 輸出: Python 爬蟲教學
print(soup.p.text) # 輸出: Hello!
註解:
title
Python 爬蟲教學/title
print(soup.title.text)
for link in soup.find_all("a"):
print(link.get("href"))
soup.find("div", class_="price").text
在 Python 中,常用的 HTML 解析工具是 BeautifulSoup(搭配 requests)。
安裝方式:
pip install requests beautifulsoup4
先用 requests 取得網頁內容:
import requests
url = "https://example.com"
response = requests.get(url)
print(response.text) # 輸出 HTML 原始碼
把 HTML 交給 BeautifulSoup 處理:
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
# 抓取標題
title = soup.title.string
print("網頁標題:", title)
links = soup.find_all("a")
for link in links:
print("文字:", link.text, "| 連結:", link["href"])
輸出:
文字: More information... | 連結: https://www.iana.org/domains/example
今天第一次用 BeautifulSoup,感覺就像把 HTML 拆開來看,用 .title 就能抓到標題,用 .find_all() 就能批次抓元素。原本覺得「爬蟲」好像很神秘,其實就是「抓網頁 → 解析 HTML → 提取想要的東西」。
原本有個exercise:擷取 iThome 鐵人賽的標題
url = "https://ithelp.ithome.com.tw/articles"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
titles = soup.find_all("a", class_="qa-list__title-link")
for i, t in enumerate(titles[:5], 1): # 只顯示前 5 筆
print(f"{i}. {t.text.strip()}")
但伺服器好像回傳空白頁面,沒有給我任何資訊
問了GPT,他說要改成加上 User-Agent的版本:
import requests
from bs4 import BeautifulSoup
url = "https://ithelp.ithome.com.tw/articles"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/114.0.0.0 Safari/537.36"
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
titles = soup.find_all("a", class_="qa-list__title-link")
for i, t in enumerate(titles[:5], 1): # 只顯示前 5 筆
print(f"{i}. {t.text.strip()}")
結果真的抓到了!
所以這邊來說明一下什麼是User-Agent!
User-Agent 是一個 HTTP 請求標頭(Header),它用來告訴伺服器「我是什麼軟體來存取你的網站」。
比如說:
我用 Chrome 瀏覽器打開網頁,瀏覽器會送一個 User-Agent 告訴伺服器:「我是 Chrome,版本多少,跑在 Windows 11 上」。如果是 iPhone 的 Safari,就會送出不同的 User-Agent。
為什麼爬蟲要加 User-Agent?
如果直接用 requests.get(url),預設的 User-Agent 是 Python 的 requests。很多網站會認出來「這不是瀏覽器,是程式!」,然後就擋掉、不給完整資料,或直接回空白。所以我們常常要偽裝成「一般使用者的瀏覽器」,加上一個瀏覽器的 User-Agent,伺服器才會回傳正常頁面。
範例:Chrome 瀏覽器的 User-Agent
Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/114.0.0.0 Safari/537.36
明天我要嘗試 初學 GUI:用 tkinter 做小視窗程式,讓程式不只是跑在黑底的終端機,而是能夠有簡單的視覺化介面!