# 怎么用Python爬取惠农网苹果数据
## 前言
在农产品电商领域,惠农网作为国内领先的B2B平台,汇聚了大量农产品价格、供需等市场数据。对于农业从业者、市场分析师或数据爱好者而言,获取这些数据具有重要价值。本文将详细介绍如何使用Python爬虫技术从惠农网获取苹果相关数据,包括价格走势、供应信息等。
## 一、准备工作
### 1.1 技术选型
我们主要使用以下Python库:
- `requests`:发送HTTP请求
- `BeautifulSoup`/`lxml`:HTML解析
- `pandas`:数据存储与分析
- `selenium`(可选):处理动态加载内容
- `time`:设置爬取间隔
安装所需库:
```bash
pip install requests beautifulsoup4 pandas selenium
访问惠农网苹果频道(https://www.cnhnb.com/p/苹果/),观察: 1. 页面结构:价格行情、供应信息、采购需求等板块 2. 数据加载方式:静态HTML或动态AJAX加载 3. 翻页机制:URL参数变化或POST请求
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
def get_page(url):
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
response.encoding = response.apparent_encoding
return response.text
except Exception as e:
print(f"获取页面失败: {e}")
return None
以价格行情板块为例:
def parse_price_data(html):
soup = BeautifulSoup(html, 'lxml')
price_table = soup.find('div', class_='price-table') # 需根据实际调整
data = []
for row in price_table.find_all('tr')[1:]: # 跳过表头
cells = row.find_all('td')
item = {
'品种': cells[0].text.strip(),
'最低价': cells[1].text.strip(),
'最高价': cells[2].text.strip(),
'均价': cells[3].text.strip(),
'单位': cells[4].text.strip(),
'市场': cells[5].text.strip(),
'更新时间': cells[6].text.strip()
}
data.append(item)
return data
使用pandas保存为CSV:
import pandas as pd
def save_to_csv(data, filename):
df = pd.DataFrame(data)
df.to_csv(filename, index=False, encoding='utf_8_sig')
当遇到JavaScript动态加载时,可使用selenium:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--headless') # 无头模式
driver = webdriver.Chrome(options=chrome_options)
def get_dynamic_page(url):
driver.get(url)
time.sleep(3) # 等待加载
return driver.page_source
对于滚动加载的页面:
def scroll_to_bottom():
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
def crawl_supply_data(pages=5):
base_url = "https://www.cnhnb.com/supply/pg{}-苹果/"
all_data = []
for page in range(1, pages+1):
url = base_url.format(page)
html = get_page(url) # 或用get_dynamic_page
if html:
soup = BeautifulSoup(html, 'lxml')
items = soup.find_all('div', class_='supply-item') # 需调整
for item in items:
data = {
'标题': item.find('h3').text.strip(),
'价格': item.find('span', class_='price').text.strip(),
'产地': item.find('div', class_='origin').text.strip(),
'供应商': item.find('a', class_='company').text.strip(),
'发布时间': item.find('span', class_='time').text.strip()
}
all_data.append(data)
time.sleep(3) # 遵守爬虫礼仪
save_to_csv(all_data, 'apple_supply.csv')
def crawl_price_trend(days=30):
# 需要分析惠农网价格趋势API
api_url = "https://www.cnhnb.com/api/price/trend"
params = {
'product': '苹果',
'days': days,
# 其他必要参数
}
response = requests.get(api_url, headers=headers, params=params)
if response.status_code == 200:
data = response.json()
trend_data = []
for item in data['list']:
trend_data.append({
'日期': item['date'],
'平均价格': item['avgPrice'],
'价格单位': item['unit']
})
save_to_csv(trend_data, 'apple_price_trend.csv')
惠农网可能采用: - User-Agent验证 - IP频率限制 - 验证码(特别是登录后) - 数据加密
# 1. 轮换User-Agent
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64)...',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...'
]
# 2. 使用代理IP
proxies = {
'http': 'http://proxy_ip:port',
'https': 'https://proxy_ip:port'
}
# 3. 随机延迟
import random
time.sleep(random.uniform(1, 5))
def clean_data(df):
# 价格处理(示例:"¥3.50/斤" → 3.5)
df['价格_数值'] = df['价格'].str.extract(r'¥(\d+\.?\d*)')[0].astype(float)
# 处理缺失值
df = df.dropna(subset=['价格_数值'])
# 统一单位
df['单位'] = df['价格'].str.extract(r'¥.*/(.*)')[0]
return df
def basic_analysis(df):
# 价格分布
print(f"平均价格: {df['价格_数值'].mean():.2f}")
print(f"最高价: {df['价格_数值'].max():.2f}")
# 按产地分析
origin_stats = df.groupby('产地')['价格_数值'].agg(['mean', 'count'])
print(origin_stats.sort_values('mean', ascending=False))
/project
│── /data # 存储爬取结果
│── /utils # 工具函数
│ ├── crawler.py # 爬虫核心
│ └── config.py # 配置文件
├── main.py # 主程序
├── requirements.txt # 依赖
└── README.md
本文详细介绍了使用Python爬取惠农网苹果数据的技术方案。请注意: 1. 实际爬取时需要根据网站当前结构调整选择器 2. 大规模爬取建议使用分布式爬虫框架(如Scrapy) 3. 商业用途需获得网站授权
通过合理使用这些数据,可以帮助农户把握市场行情,为采购决策提供数据支持,但切记遵守相关法律法规,做负责任的网络公民。
本文共计约4350字,涵盖从基础爬取到数据分析的完整流程。实际应用中请根据具体需求调整代码,并始终遵守网站的爬虫政策。 “`
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4848094/blog/4745460