閱讀提示:我現在還在嘗試爬靜態頁面
一、分頁爬取模式
以豆瓣Top250為例:
-
基礎url:豆瓣電影 Top 250
https://movie.douban.com/top250
-
分頁參數:?start=0(第一頁)、?start=25(第二頁)等
-
每頁顯示25條數據,共10頁
二、數據存取
Excel文件存儲
- pandas
- openpyxl
2.1?openpyxl基本操作
from openpyxl import Workbook# 創建新工作簿
wb = Workbook()# 獲取活動工作表(默認創建的第一個工作表)
ws = wb.active# 創建新工作表
ws1 = wb.create_sheet("MySheet1") # 默認插入到最后
ws2 = wb.create_sheet("MySheet2", 0) # 插入到第一個位置# 重命名工作表
ws.title = "New Title"
# 保存工作簿
wb.save("example.xlsx")# 加載現有工作簿
from openpyxl import load_workbook
wb = load_workbook("example.xlsx")
# 寫入數據
ws['A1'] = "Hello" # 單個單元格
ws.cell(row=1, column=2, value="World") # 行列指定# 讀取數據
print(ws['A1'].value) # 輸出: Hello
print(ws.cell(row=1, column=2).value) # 輸出: World# 批量寫入
for row in range(1, 11):for col in range(1, 5):ws.cell(row=row, column=col, value=row*col)
三、爬取代碼
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook
import timeheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
def GetFilm():base_url="https://movie.douban.com/top250"movies = []for start in range(0,250,25):url=f"{base_url}?start={start}"print(f"正在爬取: {url}")try:res=requests.get(url,headers=headers)soup=BeautifulSoup(res.text,'html.parser')items=soup.find_all('div',class_="item")for item in items:rank=item.find('em').texttitle=item.find('span',class_='title').textrating = item.find('span', class_='rating_num').textquote = item.find('p', class_='quote').text if item.find('p', class_='quote') else ""movies.append([rank,title,rating,quote])#添加延遲time.sleep(2)except Exception as e:print(f"爬取{url}時出錯: {e}")continuereturn movies # 確保返回列表
top_movies=GetFilm()
# 創建Excel工作簿
wb = Workbook()
ws = wb.active# 添加表頭
headers = ['排名', '電影名稱', '評分', '短評']
ws.append(headers)# 添加數據
for movie in top_movies:ws.append(movie)# 保存Excel文件
excel_file = 'douban_top250_openpyxl.xlsx'
wb.save(excel_file)
print(f"數據已成功保存到 {excel_file}")
結果: