在進行數據采集時,經常遇到需要從同一域名下的多個頁面提取鏈接內容的場景。本文將通過一個完整的 Python 爬蟲示例,演示如何實現多頁面鏈接的批量抓取與解析。
import requests
from bs4 import BeautifulSoup
import time
base_url = "https://example.com/list?page="
headers = {"User-Agent": "Mozilla/5.0 ..."}
all_links = []
for page in range(1, 11): # 假設抓取前 10 頁
url = base_url + str(page)
resp = requests.get(url, headers=headers)
soup = BeautifulSoup(resp.text, 'html.parser')
# 根據實際頁面結構調整選擇器
for a in soup.select('.item a[href]'):
link = a['href']
if link not in all_links:
all_links.append(link)
time.sleep(1) # 禮貌性延遲
print(f"共獲取 {len(all_links)} 條唯一鏈接")
# 後續可對 each link 發起請求獲取詳細內容
