回文章列表
Python8 分鐘閱讀2026年7月7日

Python 爬蟲入門:用 requests 抓取網頁資料

#Python#爬蟲#requests#BeautifulSoup

文章目錄

為什麼從爬蟲開始?

很多學生問我,學完 Python 基礎之後要做什麼?我的答案通常是:寫一支爬蟲。

原因很簡單——爬蟲讓你立刻感受到「程式是有用的」。你可以抓股票資料、查職缺、追蹤商品價格,馬上看到成果。

先搞懂 HTTP

瀏覽器打開網頁,背後是一個 HTTP GET 請求。requests 套件讓你用 Python 做同一件事:

import requests

response = requests.get('https://www.example.com')
print(response.status_code)  # 200 = 成功
print(response.text)          # 網頁原始碼

解析 HTML:BeautifulSoup

拿到 HTML 之後,要找到你要的資料。BeautifulSoup 讓你用 CSS 選擇器定位元素:

from bs4 import BeautifulSoup

soup = BeautifulSoup(response.text, 'html.parser')

# 找到所有 h2 標題
titles = soup.find_all('h2')
for t in titles:
    print(t.text.strip())

# 用 CSS 選擇器
items = soup.select('.product-name')

實戰:抓 PTT 熱門文章

import requests
from bs4 import BeautifulSoup

url = 'https://www.ptt.cc/bbs/Python/index.html'
headers = {'cookie': 'over18=1'}

res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')

posts = soup.select('.r-ent .title a')
for post in posts:
    print(post.text.strip(), '→', post['href'])

常見問題

Q:為什麼有些網站抓不到資料? 可能是動態載入(JavaScript 渲染),這時候要改用 Selenium,之後文章會介紹。

Q:會不會違法? 不要爬需要登入的個人資料、不要爬太快(加 time.sleep)、遵守 robots.txt 規範,一般教學用途沒問題。

下一步

掌握基礎之後,可以試試: - 儲存到 CSV:pandas DataFrame + to_csv() - 定時執行:搭配排程套件 - 動態網頁:Selenium 模擬瀏覽器

相關課程可以參考「Python 爬蟲實戰」,從基礎到 Selenium 完整練習。

相關課程

Python 爬蟲實戰

運用 requests 與 BeautifulSoup 抓取網頁資料,搭配 Selenium 處理動態網頁,並將資料存入 CSV 或資料庫。

查看課程內容