文章目录
前言(必看!)
朋友们!今天要带大家玩点硬核的——用Python爬虫+青果代理IP搞跨境电商数据!(偷偷告诉你们,我上周刚用这个方法帮朋友分析了5000+亚马逊商品数据,效果爆炸!)
一、环境准备(手把手教学版)
1.1 基础工具清单
- Python 3.8+(别问为什么不用3.7,后面requests会哭)
- requests库(HTTP请求必备神器)
- BeautifulSoup4(网页解析小能手)
- pandas(数据整理大杀器)
安装命令甩给你:
pip install requests beautifulsoup4 pandas
1.2 代理IP服务选择
为什么推荐青果代理?(亲测避坑)
- 国内IP池质量高(跨境电商网站最怕国外IP)
- 自动IP切换频率可调(再也不用手动换IP了!)
- 支持HTTPS协议(重要数据加密传输必须的)
二、代理IP配置(核心操作)
2.1 获取API接口
注册青果代理后,你会得到这样的API链接:
proxy_url = "http://api.qingguo.com/get?key=你的密钥&count=5&protocol=http"
2.2 动态IP获取函数
import requests
def get_proxy():
try:
response = requests.get(proxy_url)
return response.text.strip() # 返回格式 112.85.131.147:8888
except Exception as e:
print(f"获取代理失败!原因:{e}")
return None
三、实战案例(以亚马逊为例)
3.1 目标分析
假设我们要获取:
- 商品名称
- 价格
- 评价数量
- 星级评分
- 商品链接
3.2 请求头伪装(重点!)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Accept-Language": "en-US,en;q=0.9",
"Referer": "https://www.amazon.com/",
}
3.3 完整爬虫代码
import time
from bs4 import BeautifulSoup
def crawl_amazon(keyword):
proxy = get_proxy()
proxies = {"http": f"http://{proxy}", "https": f"http://{proxy}"}
try:
# 构造搜索URL
url = f"https://www.amazon.com/s?k={keyword}"
response = requests.get(url, headers=headers, proxies=proxies, timeout=10)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'lxml')
# 解析商品数据
products = []
for item in soup.select('div[data-component-type="s-search-result"]'):
product = {
'name': item.select_one('h2 a span').text.strip(),
'price': item.select_one('.a-price .a-offscreen').text if item.select_one('.a-price') else 'N/A',
'rating': item.select_one('.a-icon-star-small .a-icon-alt').text.split()[0] if item.select_one('.a-icon-star-small') else '0',
'reviews': item.select_one('.a-size-base').text.replace(',', '') if item.select_one('.a-size-base') else '0',
'link': 'https://www.amazon.com' + item.select_one('h2 a')['href']
}
products.append(product)
return products
elif response.status_code == 503:
print("触发验证码!需要更换IP")
return None
except Exception as e:
print(f"请求失败:{str(e)}")
return None
四、反反爬策略(血泪经验)
4.1 随机延迟设置
import random
time.sleep(random.uniform(1.5, 3.8)) # 不要用固定延迟!
4.2 IP轮换机制
retry_count = 0
while retry_count < 3:
data = crawl_amazon("wireless earphone")
if data:
break
else:
retry_count += 1
print(f"第{retry_count}次重试...")
time.sleep(5)
五、数据存储与处理
5.1 数据清洗技巧
import pandas as pd
# 转换数据类型
df = pd.DataFrame(products)
df['price'] = df['price'].str.replace('$', '').astype(float)
df['rating'] = df['rating'].astype(float)
df['reviews'] = df['reviews'].astype(int)
5.2 数据存储方案
# 保存到CSV
df.to_csv('amazon_products.csv', index=False)
# 保存到数据库(MySQL示例)
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://user:pass@localhost:3306/dbname')
df.to_sql('amazon_data', con=engine, if_exists='append', index=False)
六、法律合规提醒(超级重要!)
- 严格遵守目标网站的robots.txt协议
- 控制请求频率(建议每分钟不超过15次)
- 不采集个人隐私数据
- 商业用途需获得授权
七、常见问题解答
Q:为什么我的请求总是返回403?
A:检查三点:①请求头是否完整 ②代理IP是否有效 ③是否有验证码拦截
Q:数据抓取不全怎么办?
A:尝试:①修改CSS选择器 ②增加页面滚动加载 ③使用Selenium模拟浏览器
结语
掌握这些技巧后,你可以轻松扩展到其他平台(比如eBay、速卖通)。但切记要合理合法使用爬虫技术!如果遇到什么问题,欢迎在评论区交流讨论~
(源码已上传Github,关注后私信获取链接。代码仅供学习交流,禁止商业用途!)