在電商運營、市場分析和競品調研中,1688商品詳情數(shù)據(jù)無疑是一座“金礦”。但面對其動態(tài)加載、反爬機制,很多開發(fā)者望而卻步。今天這篇文章,就帶你手把手用Python爬蟲技術,安全、高效地獲取1688商品的核心信息!
一、為什么選擇Python爬蟲?
1688的商品頁面大多采用AJAX動態(tài)加載,傳統(tǒng)的requests庫難以獲取完整數(shù)據(jù)。為此,我們采用:
- ? Selenium:模擬瀏覽器行為,自動加載JS內容
- ? BeautifulSoup:解析HTML,提取結構化數(shù)據(jù)
- ? Pandas(可選):數(shù)據(jù)清洗與導出Excel
二、前期準備
1. 安裝依賴庫
bash
pip install selenium beautifulsoup4 pandas webdriver-manager
2. 下載ChromeDriver(自動管理)
Python
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
driver = webdriver.Chrome(ChromeDriverManager().install())
三、實戰(zhàn)案例:抓取1688商品詳情頁
我們以如下商品詳情頁為例:https://detail.1688.com/offer/123456789.html
? 步驟1:模擬訪問并滾動加載頁面
Python
import time
from selenium import webdriver
from bs4 import BeautifulSoup
def scroll_to_bottom(driver):
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
url = "https://detail.1688.com/offer/123456789.html"
driver.get(url)
scroll_to_bottom(driver)
? 步驟2:解析商品核心信息
Python
soup = BeautifulSoup(driver.page_source, 'html.parser')
product_info = {
'name': soup.select_one('h1.d-title').text.strip(),
'price': soup.select_one('.price-original').text.strip(),
'image': soup.select_one('#dt-tab img')['src'],
'description': soup.select_one('.detail-content').text.strip()[:200] + '...'
}
print("商品名稱:", product_info['name'])
print("商品價格:", product_info['price'])
print("商品圖片:", product_info['image'])
print("商品描述:", product_info['description'])
四、進階:使用1688官方API(更穩(wěn)定)
如果你希望更合規(guī)、更結構化地獲取數(shù)據(jù),可以申請1688開放平臺賬號,使用官方API:
Python
import requests, time, hashlib
def generate_sign(params, app_secret):
sorted_params = sorted(params.items())
sign_str = "&".join([f"{k}{v}" for k, v in sorted_params if k != "sign"])
return hashlib.md5((sign_str + app_secret).encode('utf-8')).hexdigest().upper()
params = {
"method": "alibaba.product.get",
"app_key": "YOUR_APP_KEY",
"product_id": "123456789",
"timestamp": str(int(time.time() * 1000)),
"format": "json",
"v": "2.0"
}
params["sign"] = generate_sign(params, "YOUR_APP_SECRET")
response = requests.get("https://gw.open.1688.com/openapi/param2/2/portals.open/api/", params=params)
data = response.json()
if data.get("code") == "0":
product = data["result"]["productInfo"]
print("商品標題:", product["subject"])
print("價格區(qū)間:", product["priceRange"])
print("最小起訂量:", product["moq"])
五、注意事項 & 反爬建議
- ? 設置請求間隔:每請求一次頁面,sleep 1~3秒
- ? 隨機User-Agent:避免被識別為機器人
- ? 使用代理IP:高并發(fā)時建議使用代理池
- ? 遵守robots.txt:尊重網(wǎng)站的爬蟲協(xié)議
- ? 合理存儲數(shù)據(jù):避免敏感信息泄露
六、總結
通過本文,你學會了:
- 如何用Selenium抓取動態(tài)加載的1688商品詳情頁
- 如何用BeautifulSoup提取商品標題、價格、圖片、描述
- 如何接入1688官方API,獲取更完整、合規(guī)的數(shù)據(jù)
- 無論是做競品分析、價格監(jiān)控、還是選品上架,這套方案都能為你提供強大支持!