# Python怎么爬取食品商務網蔬菜價格數據
網絡爬蟲是獲取公開數據的有效手段,對于農產品從業者、市場分析師或數據愛好者而言,掌握食品商務網(如foodmate、foodqs等)的蔬菜價格數據采集技術具有重要意義。本文將以Python為核心工具,詳細介紹從分析網頁結構到數據存儲的全流程實現方法。
## 一、爬蟲前的準備工作
### 1.1 目標網站分析
以典型食品行業網站"食品商務網"(www.21food.cn)為例:
- 價格數據通常存在于"行情中心"或"價格行情"欄目
- 蔬菜分類頁面URL結構示例:`/price/list-蔬菜-1.html`
- 數據呈現方式:表格形式或卡片式布局
### 1.2 技術選型
```python
必備工具庫:
- requests:網絡請求
- BeautifulSoup4/lxml:HTML解析
- pandas:數據清洗存儲
- selenium(可選):處理動態加載
- time:設置爬取間隔
可選組件:
- ProxyPool:代理IP池
- UserAgent:隨機請求頭
www.21food.cn/robots.txt
)import requests
from bs4 import BeautifulSoup
import pandas as pd
def get_vegetable_prices(page=1):
url = f"http://www.21food.cn/price/list-蔬菜-{page}.html"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
try:
response = requests.get(url, headers=headers, timeout=10)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'lxml')
# 示例解析邏輯(需根據實際頁面調整)
items = soup.select('.price-list tr')[1:] # 跳過表頭
data = []
for item in items:
cols = item.select('td')
data.append({
'品名': cols[0].text.strip(),
'價格': cols[1].text.strip(),
'單位': cols[2].text.strip(),
'市場': cols[3].text.strip(),
'日期': cols[4].text.strip()
})
return pd.DataFrame(data)
except Exception as e:
print(f"爬取失敗: {e}")
return pd.DataFrame()
# 示例調用
df = get_vegetable_prices()
print(df.head())
headers = {
"User-Agent": "Mozilla/5.0...",
"Referer": "http://www.21food.cn/",
"Accept-Language": "zh-CN,zh;q=0.9"
}
proxies = {
'http': 'http://123.456.789.012:8080',
'https': 'https://123.456.789.012:8080'
}
response = requests.get(url, proxies=proxies)
當數據通過AJAX加載時,需要采用瀏覽器自動化工具:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
chrome_options = Options()
chrome_options.add_argument("--headless") # 無頭模式
driver = webdriver.Chrome(options=chrome_options)
driver.get("http://www.21food.cn/price/")
# 等待動態加載完成
time.sleep(2)
# 模擬點擊"蔬菜"分類
driver.find_element_by_xpath('//a[contains(text(),"蔬菜")]').click()
time.sleep(1)
# 獲取渲染后的頁面源碼
soup = BeautifulSoup(driver.page_source, 'lxml')
# ...后續解析邏輯與靜態頁面相同
通過瀏覽器開發者工具(F12)捕獲XHR請求:
import json
api_url = "http://www.21food.cn/api/getPriceData"
params = {
"category": "vegetables",
"page": 1,
"size": 20
}
response = requests.get(api_url, params=params)
data = json.loads(response.text)
存儲方式 | 優點 | 缺點 |
---|---|---|
CSV文件 | 無需數據庫支持 | 查詢效率低 |
MySQL | 支持復雜查詢 | 需要配置服務 |
MongoDB | 適合非結構化數據 | 內存占用較大 |
import schedule
import time
def daily_task():
df = get_vegetable_prices()
df.to_csv(f"vegetable_prices_{time.strftime('%Y%m%d')}.csv")
# 每天上午10點執行
schedule.every().day.at("10:00").do(daily_task)
while True:
schedule.run_pending()
time.sleep(60)
/vegetable-price-spider
│── config.py # 配置文件
│── spider.py # 爬蟲主邏輯
│── utils.py # 工具函數
│── requirements.txt
└── /data # 存儲目錄
通過以上方法,您可以構建一個穩定的蔬菜價格監測系統。建議首次運行時先爬取少量頁面測試解析邏輯,確認無誤后再進行全量爬取。完整代碼示例可參考Github相關倉庫(需自行實現)。 “`
注:實際開發時需根據目標網站的具體結構調整解析邏輯,本文示例代碼可能需要修改才能正常運行。建議在爬取前先人工瀏覽目標頁面,確認數據分布結構。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。