一、項目背景與目標
攜程作為中國領先的在線旅行服務平臺,提供了豐富的機票預訂服務。其國際機票價格受多種因素影響,包括季節、節假日、航班時刻等。通過抓取攜程國際機票價格數據,我們可以進行價格趨勢分析、性價比評估以及旅行規劃建議等。
本項目的目標是:
- 利用Python爬蟲技術抓取攜程國際機票價格數據。
- 對抓取的數據進行清洗和存儲。
- 進行數據分析,包括價格趨勢、熱門航線等。
- 提供可視化結果,幫助用戶直觀了解機票價格動態。
二、 爬蟲實現步驟
1 目標分析
攜程國際機票頁面(如 **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">flights.ctrip.com</font>**
)通常采用動態加載,數據可能通過AJAX請求返回JSON格式。我們需要:
- 分析網頁請求:使用瀏覽器開發者工具(F12)查看XHR請求。
- 模擬請求:構造合理的請求頭(Headers)和參數(Params)。
- 解析數據:提取航班號、出發/到達時間、航空公司、價格等信息。
2 代碼實現
(1) 安裝依賴
(2) 獲取機票數據(靜態頁面方案)
如果攜程的機票數據可以直接通過HTML獲取(部分舊版頁面適用),可以使用 **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">requests + Beautifu</font>**
import requests
from bs4 import BeautifulSoup
import pandas as pddef scrape_ctrip_flights(departure, arrival, date):url = f"https://flights.ctrip.com/international/{departure}-{arrival}?depdate={date}"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"}response = requests.get(url, headers=headers)soup = BeautifulSoup(response.text, 'html.parser')flights = []for flight in soup.select('.flight-item'):airline = flight.select_one('.airline-name').text.strip()departure_time = flight.select_one('.depart-time').text.strip()arrival_time = flight.select_one('.arrival-time').text.strip()price = flight.select_one('.price').text.strip()flights.append({'Airline': airline,'DepartureTime': departure_time,'ArrivalTime': arrival_time,'Price': price})return pd.DataFrame(flights)# 示例:抓取上海到東京的2023-12-01航班
df = scrape_ctrip_flights('SHA', 'TYO', '2023-12-01')
print(df.head())
(3) 動態頁面抓取(Selenium方案)
如果數據是動態加載的,需使用 **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">Selenium</font>**
模擬瀏覽器操作:
from selenium import webdriver
from selenium.webdriver.common.by import By
import timedef scrape_ctrip_dynamic(departure, arrival, date):driver = webdriver.Chrome() # 需安裝ChromeDriverurl = f"https://flights.ctrip.com/international/{departure}-{arrival}?depdate={date}"driver.get(url)time.sleep(5) # 等待頁面加載flights = []for flight in driver.find_elements(By.CSS_SELECTOR, '.flight-item'):airline = flight.find_element(By.CSS_SELECTOR, '.airline-name').textdeparture_time = flight.find_element(By.CSS_SELECTOR, '.depart-time').textarrival_time = flight.find_element(By.CSS_SELECTOR, '.arrival-time').textprice = flight.find_element(By.CSS_SELECTOR, '.price').textflights.append({'Airline': airline,'DepartureTime': departure_time,'ArrivalTime': arrival_time,'Price': price})driver.quit()return pd.DataFrame(flights)# 示例:動態抓取數據
df = scrape_ctrip_dynamic('SHA', 'TYO', '2023-12-01')
print(df.head())
(4) 反爬策略
攜程可能有反爬機制,需采取以下措施:
- 隨機User-Agent:避免被識別為爬蟲。
- IP代理池:防止IP被封禁。
- 請求間隔:避免高頻訪問。
示例(使用 **<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">fake_useragent</font>**
和代理):
from fake_useragent import UserAgent
import requests# 初始化UserAgent對象
ua = UserAgent()# 設置請求頭
headers = {"User-Agent": ua.random,"Accept-Language": "en-US,en;q=0.9"
}# 設置代理信息
proxyHost = "www.16yun.cn"
proxyPort = "5445"
proxyUser = "16QMSOML"
proxyPass = "280651"# 構造代理服務器的認證信息
proxy_auth = f"{proxyUser}:{proxyPass}"# 構造代理服務器的URL
proxies = {"http": f"http://{proxy_auth}@{proxyHost}:{proxyPort}","https": f"https://{proxy_auth}@{proxyHost}:{proxyPort}"
}# 目標URL
url = "https://example.com" # 替換為你的目標URL# 發送請求
response = requests.get(url, headers=headers, proxies=proxies)# 打印響應內容
print(response.text)
三、 數據分析與可視化
(1) 數據清洗
# 轉換價格格式(如 "¥2,500" → 2500)
df['Price'] = df['Price'].str.replace('¥', '').str.replace(',', '').astype(float)# 按價格排序
df_sorted = df.sort_values('Price')
print(df_sorted.head())
(2) 價格分布可視化
import matplotlib.pyplot as plt
import seaborn as snsplt.figure(figsize=(10, 6))
sns.histplot(df['Price'], bins=20, kde=True)
plt.title('International Flight Price Distribution (Shanghai to Tokyo)')
plt.xlabel('Price (¥)')
plt.ylabel('Frequency')
plt.show()
(3) 航空公司價格對比
plt.figure(figsize=(12, 6))
sns.boxplot(x='Airline', y='Price', data=df)
plt.xticks(rotation=45)
plt.title('Flight Price Comparison by Airline')
plt.show()
四.、結論
本文介紹了如何使用Python爬取攜程國際機票數據,并進行分析與可視化。關鍵點包括:
- 網頁分析:確定數據加載方式(靜態/動態)。
- 爬蟲實現:使用
**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">Requests</font>**
或**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">Selenium</font>**
抓取數據。 - 反爬策略:合理設置請求頭、代理和訪問頻率。
- 數據分析:利用
**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">Pandas</font>**
和**<font style="color:rgb(64, 64, 64);background-color:rgb(236, 236, 236);">Matplotlib</font>**
進行價格趨勢分析。