📌 第 8 小時:網路爬蟲(Web Scraping)
網路爬蟲(Web Scraping)是指使用程式自動從網站抓取資料,Python 提供多種強大的爬蟲工具,例如:
requests
:負責發送 HTTP 請求,取得網頁原始碼BeautifulSoup
:解析 HTML,提取特定資料lxml
:更快的 HTML 解析器Selenium
:可用來爬取動態網頁(JavaScript 生成的內容)
🔹 1. 使用 requests
取得網頁內容
首先,我們需要使用 requests
發送 HTTP 請求 來獲取網頁內容。
🟢 安裝 requests
請在終端機(或 CMD)執行:
pip install requests
🟢 發送 GET 請求
import requests
url = "https://www.example.com"
response = requests.get(url)
print(response.status_code) # 200 代表請求成功
print(response.text) # 顯示網頁的 HTML 內容
📌 重點
requests.get(url)
用於發送 GET 請求response.status_code
取得 HTTP 狀態碼(200 代表成功)response.text
取得 HTML 原始碼
🔹 2. 使用 BeautifulSoup
解析 HTML
BeautifulSoup 是 Python 的 HTML 解析工具,可用來提取網頁中的標題、超連結、圖片等內容。
🟢 安裝 BeautifulSoup
pip install beautifulsoup4
🟢 解析 HTML
from bs4 import BeautifulSoup
html = """
<html>
<head><title>Python 爬蟲測試</title></head>
<body>
<h1>Hello, Web Scraping!</h1>
<p class="content">這是一段測試的 HTML 內容。</p>
<a href="https://www.python.org">Python 官方網站</a>
</body>
</html>
"""
soup = BeautifulSoup(html, "html.parser")
print(soup.title.text) # 取得 <title> 內容
print(soup.h1.text) # 取得 <h1> 內容
print(soup.p.text) # 取得 <p> 內容
print(soup.a["href"]) # 取得 <a> 標籤的 href 屬性值
📌 解析 HTML 常見方法
方法 | 作用 |
---|---|
soup.title |
取得 <title> 標籤 |
soup.h1 |
取得 <h1> 標籤 |
soup.find("p") |
找到第一個 <p> 標籤 |
soup.find_all("a") |
找到所有 <a> 標籤 |
🔹 3. 爬取真實網站
我們來嘗試爬取 Python 官方網站的標題與超連結。
🟢 爬取網站標題與連結
import requests
from bs4 import BeautifulSoup
url = "https://www.python.org"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 取得標題
print("網站標題:", soup.title.text)
# 取得所有超連結
for link in soup.find_all("a"):
print(link.get("href")) # 取得 <a> 標籤的 href 屬性
📌 重點
soup.find_all("a")
找到所有<a>
標籤link.get("href")
取得超連結的href
屬性
🔹 4. 使用 requests
爬取 JSON API
除了 HTML 內容,許多網站提供 API 來回傳 JSON 格式的數據。
🟢 範例:爬取 JSON API
import requests
url = "https://jsonplaceholder.typicode.com/todos/1"
response = requests.get(url)
data = response.json() # 轉換為 Python 字典
print(data)
📌 JSON 解析
response.json()
會將 JSON 轉換為 Python 字典- 可以使用
data["key"]
來存取值
🔹 5. 使用 Selenium
爬取動態網頁
有些網站的內容是 JavaScript 動態生成 的,requests
無法直接取得內容,這時候需要用 Selenium
模擬瀏覽器行為。
🟢 安裝 Selenium
pip install selenium
此外,你需要 下載 ChromeDriver,可以從 這裡下載。
🟢 使用 Selenium
爬取動態網頁
from selenium import webdriver
driver = webdriver.Chrome() # 使用 Chrome 瀏覽器
driver.get("https://www.python.org") # 開啟網站
print(driver.title) # 取得網頁標題
driver.quit() # 關閉瀏覽器
📌 適用場景
- 爬取 JavaScript 生成的內容
- 模擬登入、點擊、填寫表單等行為
🔹 6. 爬取表格數據
某些網站的數據是表格格式,我們可以使用 pandas
解析。
🟢 安裝 pandas
pip install pandas
🟢 使用 pandas
解析 HTML 表格
import pandas as pd
url = "https://www.w3schools.com/html/html_tables.asp"
tables = pd.read_html(url) # 讀取所有表格
print(tables[0]) # 顯示第一個表格
📌 適用於金融數據、股票市場、統計表格等網站。
🔹 7. 處理爬蟲封鎖
部分網站會偵測爬蟲並進行封鎖,解決方案: ✅ User-Agent 伪装
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
✅ 使用 time.sleep()
隨機延遲
import time
time.sleep(3) # 停 3 秒
✅ 使用代理伺服器
proxies = {"http": "http://your_proxy_here"}
response = requests.get(url, proxies=proxies)
📌 第 8 小時小結
✅ 使用 requests
取得網頁 HTML
✅ 用 BeautifulSoup
解析 HTML,提取標題、超連結等內容
✅ 爬取 JSON API,獲取結構化數據
✅ Selenium
可模擬瀏覽器操作,爬取動態網頁
✅ pandas
解析 HTML 表格,獲取表格數據
✅ 避免封鎖的方法:User-Agent、延遲請求、代理伺服器
學完這一章,你已經掌握 Python 網路爬蟲的基礎,下一步將進入 資料分析,讓你學會如何處理與視覺化數據!🚀
沒有留言:
張貼留言