跳到內容

網路爬蟲

網路爬蟲就是用程式自動去抓網頁上的資料。這個專題用兩個很常見的套件:requests 負責把網頁抓下來,BeautifulSoup 負責從一堆 HTML 裡挑出你要的內容。

Terminal window
uv add requests beautifulsoup4

沒用 uv 的話:

Terminal window
pip install requests beautifulsoup4

requests.get() 會去抓指定網址,回傳的物件裡有這個網頁的內容:

import requests
response = requests.get("https://example.com")
response.encoding = "utf-8"
print(response.status_code)
print(response.text)
  • response.status_code:狀態碼,200 代表成功,404 代表找不到頁面。
  • response.text:整個網頁的 HTML 原始碼。
  • response.encoding = "utf-8":指定編碼,避免中文變成亂碼。

response.text 是一大坨 HTML,直接看很難用。把它交給 BeautifulSoup,就能用標籤名稱把內容挑出來:

import requests
from bs4 import BeautifulSoup
response = requests.get("https://example.com")
soup = BeautifulSoup(response.text, "html.parser")
title = soup.find("h1")
print(title.text)
for link in soup.find_all("a"):
print(link.get("href"))
  • BeautifulSoup(response.text, "html.parser"):把 HTML 交給 BeautifulSoup 解析。
  • soup.find("h1"):找出第一個 <h1> 標籤。
  • soup.find_all("a"):找出所有 <a> 連結標籤,回傳一個串列,可以用 for 走過。
  • .text 拿到標籤裡的文字;.get("href") 拿到連結的網址。

想抓不同的東西,就換 find / find_all 裡的標籤名稱,例如 "p"(段落)、"img"(圖片)、"td"(表格欄位)。

爬別人的網站,有幾件事要放在心上:

  • 看看對方允不允許:很多網站的 /robots.txt(例如 https://example.com/robots.txt)會寫明哪些頁面歡迎爬、哪些不希望被爬。
  • 不要抓太快、太頻繁:短時間內狂抓會對別人的伺服器造成負擔,也容易被封鎖。需要抓很多頁時,記得每次之間停一下(用 time.sleep())。
  • 尊重資料的使用規範:抓下來的資料怎麼用,要留意對方網站的服務條款,尤其別拿去做商業用途或大量轉載。
  • 找一個你常看的網站,把它的所有標題(h1h2)抓下來印出。
  • 把抓到的連結存進一個檔案(用檔案讀寫那章的 open)。