Python + Requests庫(kù)爬取動(dòng)態(tài)Ajax分頁(yè)數(shù)據(jù)的完整流程
引言
在當(dāng)今的互聯(lián)網(wǎng)環(huán)境中,許多網(wǎng)站采用Ajax(Asynchronous JavaScript and XML)技術(shù)動(dòng)態(tài)加載數(shù)據(jù),以提高用戶體驗(yàn)。傳統(tǒng)的爬蟲方法(如直接解析HTML)無(wú)法獲取這些動(dòng)態(tài)生成的內(nèi)容,因此需要分析Ajax請(qǐng)求,模擬瀏覽器發(fā)送HTTP請(qǐng)求來(lái)獲取數(shù)據(jù)。
本文將介紹如何使用Python + Requests庫(kù)爬取動(dòng)態(tài)Ajax分頁(yè)數(shù)據(jù),包括:
- 分析Ajax請(qǐng)求,找到數(shù)據(jù)接口
- 模擬請(qǐng)求參數(shù),構(gòu)造翻頁(yè)邏輯
- 解析返回?cái)?shù)據(jù)(通常是JSON格式)
- 存儲(chǔ)數(shù)據(jù)(如CSV或數(shù)據(jù)庫(kù))
我們將以某電商網(wǎng)站(模擬案例)為例,演示如何爬取分頁(yè)商品數(shù)據(jù)。
1. 分析Ajax請(qǐng)求
1.1 目標(biāo)網(wǎng)站分析
假設(shè)目標(biāo)網(wǎng)站的商品列表采用Ajax動(dòng)態(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)前頁(yè)碼**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">size</font>**:每頁(yè)數(shù)據(jù)量
1.2 使用瀏覽器開發(fā)者工具
- 打開Chrome/Firefox開發(fā)者工具(F12)
- 進(jìn)入Network(網(wǎng)絡(luò))選項(xiàng)卡
- 選擇XHR(Ajax請(qǐng)求)
- 翻頁(yè)時(shí)觀察新增的請(qǐng)求,找到數(shù)據(jù)接口
https://example.com/ajax-analysis.png
1.3 確定請(qǐng)求參數(shù)
觀察請(qǐng)求的:
- URL(是否包含頁(yè)碼參數(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>**等) - 請(qǐng)求方式(GET/POST)
- 返回?cái)?shù)據(jù)格式(通常是JSON)
2. Python + Requests 實(shí)現(xiàn)爬取
2.1 安裝依賴庫(kù)
2.2 構(gòu)造請(qǐng)求函數(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"請(qǐng)求失敗,狀態(tài)碼:{response.status_code}")
return None2.3 解析數(shù)據(jù)并翻頁(yè)
def crawl_ajax_pages(max_pages=5):
all_products = []
for page in range(1, max_pages + 1):
print(f"正在爬取第 {page} 頁(yè)...")
data = fetch_ajax_data(page)
if data and "products" in data:
all_products.extend(data["products"])
else:
print(f"第 {page} 頁(yè)無(wú)數(shù)據(jù)或解析失敗")
return all_products2.4 存儲(chǔ)數(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:防止被識(shí)別為爬蟲
- 請(qǐng)求間隔:避免被封IP
- 代理IP:應(yīng)對(duì)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) # 避免請(qǐng)求過快
# 其余代碼同上...3.2 異常處理
try:
response = requests.get(url, headers=headers, params=params, timeout=10)
response.raise_for_status() # 檢查HTTP錯(cuò)誤
except requests.exceptions.RequestException as e:
print(f"請(qǐng)求異常:{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) # 防止請(qǐng)求過快
# 添加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} 頁(yè)請(qǐng)求失敗:{e}")
return None
def crawl_ajax_pages(max_pages=5):
all_products = []
for page in range(1, max_pages + 1):
print(f"正在爬取第 {page} 頁(yè)...")
data = fetch_ajax_data(page)
if data and "products" in data:
all_products.extend(data["products"])
else:
print(f"第 {page} 頁(yè)無(wú)數(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庫(kù)爬取動(dòng)態(tài)Ajax分頁(yè)數(shù)據(jù),核心步驟包括:
- 分析Ajax請(qǐng)求(使用瀏覽器開發(fā)者工具)
- 模擬請(qǐng)求參數(shù)(Headers、Query Params)
- 翻頁(yè)邏輯實(shí)現(xiàn)(循環(huán)請(qǐng)求不同頁(yè)碼)
- 數(shù)據(jù)存儲(chǔ)(CSV、數(shù)據(jù)庫(kù)等)
- 反爬優(yōu)化(隨機(jī)UA、代理IP、請(qǐng)求間隔)
這種方法適用于大多數(shù)動(dòng)態(tài)加載數(shù)據(jù)的網(wǎng)站,如電商、新聞、社交媒體等。如果需要更復(fù)雜的動(dòng)態(tài)渲染(如JavaScript生成內(nèi)容),可結(jié)合Selenium或Playwright實(shí)現(xiàn)。
到此這篇關(guān)于Python + Requests庫(kù)爬取動(dòng)態(tài)Ajax分頁(yè)數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Python Requests庫(kù) Ajax分頁(yè)數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python3+Pycharm+PyQt5環(huán)境搭建步驟圖文詳解
這篇文章主要介紹了Python3+Pycharm+PyQt5環(huán)境搭建步驟圖文詳解,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05
Python Numpy庫(kù)datetime類型的處理詳解
這篇文章主要介紹了Python Numpy庫(kù)datetime類型的處理詳解,Python中自帶的處理時(shí)間的模塊就有time 、datetime、calendar,另外還有擴(kuò)展的第三方庫(kù),如dateutil等等。。當(dāng)我們用NumPy庫(kù)做數(shù)據(jù)分析時(shí),如何轉(zhuǎn)換時(shí)間呢?需要的朋友可以參考下2019-07-07
python基礎(chǔ)教程之簡(jiǎn)單入門說明(變量和控制語(yǔ)言使用方法)
這篇文章主要介紹了開始學(xué)習(xí)python的第一步需要知道的知識(shí)(變量和控制語(yǔ)言使用方法),需要的朋友可以參考下2014-03-03
Python定時(shí)任務(wù)APScheduler的實(shí)例實(shí)例詳解
APScheduler 支持三種調(diào)度任務(wù):固定時(shí)間間隔,固定時(shí)間點(diǎn)(日期),Linux 下的 Crontab 命令。這篇文章主要介紹了Python定時(shí)任務(wù)APScheduler的使用,需要的朋友可以參考下2019-07-07
Python實(shí)現(xiàn)購(gòu)物程序思路及代碼
本文給大家分享的是使用Python實(shí)現(xiàn)的購(gòu)物小程序的思路要求以及相關(guān)代碼,非常的簡(jiǎn)單實(shí)用,有需要的小伙伴可以參考下2017-07-07
在python3中使用Supervisor的詳細(xì)教程
Supervisor是用Python開發(fā)的一個(gè)client/server服務(wù),是Linux/Unix系統(tǒng)下的一個(gè)進(jìn)程管理工具,不支持Windows系統(tǒng),本文給大家介紹在python3中使用Supervisor的方法,感興趣的朋友一起看看吧2022-01-01
python實(shí)現(xiàn)批量解析郵件并下載附件
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)批量解析郵件并下載附件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06

