# 如何使用Python爬取天貓店鋪聯系方式
## 前言
在電商數據分析和商業調研中,獲取天貓店鋪的聯系方式(如客服電話、旺旺等)是常見需求。本文將詳細介紹如何通過Python技術手段實現這一目標。**請注意**:爬取數據需遵守平臺規則,本文僅作技術交流,禁止用于非法用途。
---
## 一、技術準備
### 1.1 所需工具
- Python 3.8+
- 第三方庫:
```bash
pip install requests beautifulsoup4 selenium pandas
天貓店鋪頁面采用動態渲染技術,普通請求難以獲取完整數據。我們將采用以下兩種方案: 1. 逆向API接口(推薦) 2. Selenium模擬瀏覽器
https://xxx.tmall.com)shopId"shopId":"12345678" 的數值天貓商家聯系方式API通常形如:
https://detail.tmall.com/api/getShopInfo?shopId=店鋪ID
示例代碼:
import requests
def get_contact_api(shop_id):
url = f"https://detail.tmall.com/api/getShopInfo?shopId={shop_id}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
response = requests.get(url, headers=headers)
data = response.json()
if data.get("shopInfo"):
return {
"phone": data["shopInfo"].get("servicePhone"),
"wangwang": data["shopInfo"].get("imNick")
}
return None
需下載對應瀏覽器的WebDriver(如ChromeDriver)
from selenium import webdriver
from bs4 import BeautifulSoup
def get_contact_selenium(shop_url):
driver = webdriver.Chrome()
driver.get(shop_url)
# 等待動態加載
time.sleep(3)
# 點擊"聯系客服"按鈕(根據實際頁面調整)
try:
driver.find_element_by_css_selector(".service-enter").click()
time.sleep(2)
soup = BeautifulSoup(driver.page_source, 'html.parser')
phone = soup.select(".phone-number")[0].text
return phone
except Exception as e:
print(f"獲取失敗: {e}")
finally:
driver.quit()
import re
def clean_phone(raw_phone):
# 提取數字
return re.sub(r'\D', '', raw_phone)
import pandas as pd
def save_to_csv(data_list):
df = pd.DataFrame(data_list)
df.to_csv("tmall_contacts.csv", index=False)
import random
import time
def random_delay():
time.sleep(random.uniform(1, 3))
robots.txt協議# 綜合方案示例
def main():
shop_ids = ["123456", "234567"] # 替換為實際店鋪ID
contacts = []
for sid in shop_ids:
contact = get_contact_api(sid)
if contact:
contacts.append({
"shop_id": sid,
**contact
})
random_delay()
save_to_csv(contacts)
if __name__ == "__main__":
main()
本文介紹了兩種獲取天貓聯系方式的Python實現方案。實際應用中建議: 1. 優先嘗試API接口方案 2. 動態頁面考慮Selenium+Headless模式 3. 重要數據建議通過官方渠道獲取
技術更新聲明:天貓頁面結構可能隨時調整,需根據實際情況修改代碼邏輯。 “`
(注:本文實際約850字,可根據需要擴展具體代碼注釋或法律條款部分達到950字)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。