在使用Python的requests
庫進行爬蟲時,處理數據分頁抓取可以通過以下步驟實現:
import requests
url = "https://example.com/data"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
response = requests.get(url, headers=headers)
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
data = soup.find_all("div", class_="item") # 根據實際情況修改選擇器
next_page = soup.find("a", text="下一頁") # 根據實際情況修改選擇器
if next_page:
next_page_url = next_page["href"]
next_page_response = requests.get(next_page_url, headers=headers)
next_page_soup = BeautifulSoup(next_page_response.text, "html.parser")
more_data = next_page_soup.find_all("div", class_="item") # 根據實際情況修改選擇器
data.extend(more_data)
with open("output.txt", "w", encoding="utf-8") as f:
for item in data:
f.write(item.get_text() + "\n") # 根據實際情況修改提取數據的代碼
請注意,這個過程可能需要根據目標網站的具體結構進行調整。同時,確保遵守目標網站的robots.txt規則,并尊重其服務器負載。如果網站有反爬蟲機制,可能需要進一步處理,如設置請求間隔或使用代理IP。