Python + Requests庫爬取動態(tài)Ajax分頁數(shù)據(jù)的完整流程
引言
在當(dāng)今的互聯(lián)網(wǎng)環(huán)境中,許多網(wǎng)站采用Ajax(Asynchronous JavaScript and XML)技術(shù)動態(tài)加載數(shù)據(jù),以提高用戶體驗(yàn)。傳統(tǒng)的爬蟲方法(如直接解析HTML)無法獲取這些動態(tài)生成的內(nèi)容,因此需要分析Ajax請求,模擬瀏覽器發(fā)送HTTP請求來獲取數(shù)據(jù)。
本文將介紹如何使用Python + Requests庫爬取動態(tài)Ajax分頁數(shù)據(jù),包括:
- 分析Ajax請求,找到數(shù)據(jù)接口
- 模擬請求參數(shù),構(gòu)造翻頁邏輯
- 解析返回數(shù)據(jù)(通常是JSON格式)
- 存儲數(shù)據(jù)(如CSV或數(shù)據(jù)庫)
我們將以某電商網(wǎng)站(模擬案例)為例,演示如何爬取分頁商品數(shù)據(jù)。
1. 分析Ajax請求
1.1 目標(biāo)網(wǎng)站分析
假設(shè)目標(biāo)網(wǎng)站的商品列表采用Ajax動態(tài)加載,URL結(jié)構(gòu)如下:
https://example.com/api/products?page=1&size=10
**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">page</font>**:當(dāng)前頁碼**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">size</font>**:每頁數(shù)據(jù)量
1.2 使用瀏覽器開發(fā)者工具
- 打開Chrome/Firefox開發(fā)者工具(F12)
- 進(jìn)入Network(網(wǎng)絡(luò))選項(xiàng)卡
- 選擇XHR(Ajax請求)
- 翻頁時觀察新增的請求,找到數(shù)據(jù)接口
https://example.com/ajax-analysis.png
1.3 確定請求參數(shù)
觀察請求的:
- URL(是否包含頁碼參數(shù))
- Headers(是否需要
**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">User-Agent</font>**、**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">Referer</font>**等) - 請求方式(GET/POST)
- 返回數(shù)據(jù)格式(通常是JSON)
2. Python + Requests 實(shí)現(xiàn)爬取
2.1 安裝依賴庫
2.2 構(gòu)造請求函數(shù)
import requests
import pandas as pd
def fetch_ajax_data(page):
url = "https://example.com/api/products"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Referer": "https://example.com/products",
}
params = {
"page": page,
"size": 10,
}
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
return response.json() # 假設(shè)返回的是JSON數(shù)據(jù)
else:
print(f"請求失敗,狀態(tài)碼:{response.status_code}")
return None2.3 解析數(shù)據(jù)并翻頁
def crawl_ajax_pages(max_pages=5):
all_products = []
for page in range(1, max_pages + 1):
print(f"正在爬取第 {page} 頁...")
data = fetch_ajax_data(page)
if data and "products" in data:
all_products.extend(data["products"])
else:
print(f"第 {page} 頁無數(shù)據(jù)或解析失敗")
return all_products2.4 存儲數(shù)據(jù)(CSV)
def save_to_csv(data, filename="products.csv"):
df = pd.DataFrame(data)
df.to_csv(filename, index=False, encoding="utf-8-sig")
print(f"數(shù)據(jù)已保存至 {filename}")
# 執(zhí)行爬取
if __name__ == "__main__":
products = crawl_ajax_pages(max_pages=5)
if products:
save_to_csv(products)3. 進(jìn)階優(yōu)化
3.1 處理反爬機(jī)制
- 隨機(jī)User-Agent:防止被識別為爬蟲
- 請求間隔:避免被封IP
- 代理IP:應(yīng)對IP限制
import time
from fake_useragent import UserAgent
def fetch_ajax_data_safe(page):
ua = UserAgent()
headers = {
"User-Agent": ua.random,
"Referer": "https://example.com/products",
}
time.sleep(1) # 避免請求過快
# 其余代碼同上...3.2 異常處理
try:
response = requests.get(url, headers=headers, params=params, timeout=10)
response.raise_for_status() # 檢查HTTP錯誤
except requests.exceptions.RequestException as e:
print(f"請求異常:{e}")
return None3.3 多線程/異步爬?。ㄌ岣咝剩?/h3>
import concurrent.futures
def crawl_with_threads(max_pages=5, workers=3):
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
futures = [executor.submit(fetch_ajax_data, page) for page in range(1, max_pages + 1)]
all_products = []
for future in concurrent.futures.as_completed(futures):
data = future.result()
if data:
all_products.extend(data.get("products", []))
return all_products
import concurrent.futures
def crawl_with_threads(max_pages=5, workers=3):
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
futures = [executor.submit(fetch_ajax_data, page) for page in range(1, max_pages + 1)]
all_products = []
for future in concurrent.futures.as_completed(futures):
data = future.result()
if data:
all_products.extend(data.get("products", []))
return all_products4. 完整代碼示例
import requests
import pandas as pd
import time
from fake_useragent import UserAgent
# 代理服務(wù)器配置
proxyHost = "www.16yun.cn"
proxyPort = "5445"
proxyUser = "16QMSOML"
proxyPass = "280651"
# 構(gòu)造代理字典
proxies = {
"http": f"http://{proxyUser}:{proxyPass}@{proxyHost}:{proxyPort}",
"https": f"http://{proxyUser}:{proxyPass}@{proxyHost}:{proxyPort}",
}
def fetch_ajax_data(page):
ua = UserAgent()
url = "https://example.com/api/products"
headers = {
"User-Agent": ua.random,
"Referer": "https://example.com/products",
}
params = {
"page": page,
"size": 10,
}
try:
time.sleep(1) # 防止請求過快
# 添加proxies參數(shù)使用代理
response = requests.get(
url,
headers=headers,
params=params,
timeout=10,
proxies=proxies
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"第 {page} 頁請求失?。簕e}")
return None
def crawl_ajax_pages(max_pages=5):
all_products = []
for page in range(1, max_pages + 1):
print(f"正在爬取第 {page} 頁...")
data = fetch_ajax_data(page)
if data and "products" in data:
all_products.extend(data["products"])
else:
print(f"第 {page} 頁無數(shù)據(jù)或解析失敗")
return all_products
def save_to_csv(data, filename="products.csv"):
df = pd.DataFrame(data)
df.to_csv(filename, index=False, encoding="utf-8-sig")
print(f"數(shù)據(jù)已保存至 {filename}")
if __name__ == "__main__":
products = crawl_ajax_pages(max_pages=5)
if products:
save_to_csv(products)5. 總結(jié)
本文介紹了如何使用Python + Requests庫爬取動態(tài)Ajax分頁數(shù)據(jù),核心步驟包括:
- 分析Ajax請求(使用瀏覽器開發(fā)者工具)
- 模擬請求參數(shù)(Headers、Query Params)
- 翻頁邏輯實(shí)現(xiàn)(循環(huán)請求不同頁碼)
- 數(shù)據(jù)存儲(CSV、數(shù)據(jù)庫等)
- 反爬優(yōu)化(隨機(jī)UA、代理IP、請求間隔)
這種方法適用于大多數(shù)動態(tài)加載數(shù)據(jù)的網(wǎng)站,如電商、新聞、社交媒體等。如果需要更復(fù)雜的動態(tài)渲染(如JavaScript生成內(nèi)容),可結(jié)合Selenium或Playwright實(shí)現(xiàn)。
到此這篇關(guān)于Python + Requests庫爬取動態(tài)Ajax分頁數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Python Requests庫 Ajax分頁數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用python對多個txt文件中的數(shù)據(jù)進(jìn)行篩選的方法
今天小編就為大家分享一篇使用python對多個txt文件中的數(shù)據(jù)進(jìn)行篩選的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
python通過對字典的排序,對json字段進(jìn)行排序的實(shí)例
今天小編就為大家分享一篇python通過對字典的排序,對json字段進(jìn)行排序的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
python使用matplotlib庫生成隨機(jī)漫步圖
這篇文章主要為大家詳細(xì)介紹了使用Python的matplotlib庫生成隨機(jī)漫步圖,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-08-08
正則表達(dá)式在Python中的應(yīng)用小結(jié)
正則表達(dá)式是一種強(qiáng)大的文本模式匹配工具,它可以幫助我們快速地檢索、替換或提取字符串中的特定模式,在本文中,我將通過一些示例代碼,詳細(xì)介紹正則表達(dá)式在Python中的應(yīng)用,感興趣的朋友一起看看吧2024-07-07
Python實(shí)現(xiàn)程序開機(jī)自啟動的常見方案
在 Python 中實(shí)現(xiàn)程序開機(jī)自啟動,有多種方法可以完成,本文為大家整理了一些常見的方法,適用于不同的操作系統(tǒng),感興趣的小伙伴可以了解下2026-03-03
Pytorch GPU顯存充足卻顯示out of memory的解決方式
今天小編就為大家分享一篇Pytorch GPU顯存充足卻顯示out of memory的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01

