一、什么是爬蟲?
網絡爬蟲(Web Crawler),又稱網頁蜘蛛,是一種自動抓取互聯網信息的程序。爬蟲會模擬人的瀏覽行為,向網站發送請求,然后獲取網頁內容并提取有用的數據。
二、Python爬蟲的基本原理
爬蟲的基本工作流程如下:
-
發送請求:使用
requests
等庫向目標網站發送 HTTP 請求。 -
獲取響應:服務器返回 HTML 頁面內容。
-
解析數據:使用
BeautifulSoup
、lxml
或re
提取所需的數據。 -
保存數據:將數據保存為 CSV、Excel、數據庫等格式。
三、搭建一個簡單的 Python 爬蟲
1. 安裝必要的庫
pip install requests beautifulsoup4
2. 示例目標:爬取豆瓣電影 Top 250 的電影名稱
地址:豆瓣電影 Top 250
3. 基本代碼結構
import requests
from bs4 import BeautifulSoup# 設置請求頭,模擬瀏覽器訪問
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'
}# 循環每一頁(每頁25部電影,共10頁)
for page in range(0, 250, 25):url = f'https://movie.douban.com/top250?start={page}'response = requests.get(url, headers=headers)if response.status_code == 200:soup = BeautifulSoup(response.text, 'html.parser')movie_tags = soup.find_all('div', class_='hd')for tag in movie_tags:title = tag.a.span.textprint(title)else:print(f"請求失敗:{response.status_code}")
4. 運行結果(部分)
肖申克的救贖
霸王別姬
阿甘正傳
這個殺手不太冷
...
四、常見反爬機制及應對
1. User-Agent 檢查
→ 解決方法:自定義請求頭。
2. 頻繁請求封 IP
→ 解決方法:使用 time.sleep()
控制請求間隔,或使用代理。
3. 動態加載頁面(JS 渲染)
→ 解決方法:使用 Selenium 或 Playwright 等瀏覽器自動化工具。
五、進階:使用 Selenium 爬取動態網頁
pip install selenium
代碼示例(以百度為例):
from selenium import webdriver
from selenium.webdriver.common.by import By
import timedriver = webdriver.Chrome()
driver.get('https://www.baidu.com')search_box = driver.find_element(By.ID, 'kw')
search_box.send_keys('Python 爬蟲')search_button = driver.find_element(By.ID, 'su')
search_button.click()time.sleep(2)print(driver.page_source) # 打印網頁HTMLdriver.quit()
六、數據保存(CSV 示例)
import csvwith open('movies.csv', 'w', newline='', encoding='utf-8') as f:writer = csv.writer(f)writer.writerow(['電影名稱'])for title in movie_titles:writer.writerow([title])
七、建議與注意事項
-
尊重網站的 Robots.txt 協議,不惡意爬取。
-
控制請求頻率,避免造成服務器負擔。
-
爬蟲只是工具,數據的合法使用才是重點。
八、結語
本教程只是 Python 爬蟲的入門介紹,后續還可以學習更多內容,比如:
-
Scrapy 框架
-
多線程爬蟲
-
分布式爬蟲(如結合 Redis)
-
反爬機制繞過技巧
-
數據可視化與分析
如果你剛入門 Python 爬蟲,建議從小項目練起,熟悉請求與解析的流程,再逐步擴展。