# 如何通過Python爬取網頁抖音熱門視頻

## 前言
在當今短視頻爆發的時代,抖音作為國內領先的短視頻平臺,每天產生數以億計的視頻內容。對于數據分析師、市場研究人員或內容創作者來說,獲取抖音熱門視頻數據具有重要價值。本文將詳細介紹如何使用Python技術棧實現抖音網頁版熱門視頻的爬取。
---
## 一、準備工作
### 1.1 技術棧選擇
- **Python 3.8+**:基礎編程語言
- **Requests**:網絡請求庫
- **BeautifulSoup4**:HTML解析庫
- **Selenium**:自動化測試工具(用于處理動態加載)
- **PyExecJS**:執行JavaScript代碼
### 1.2 環境安裝
```bash
pip install requests beautifulsoup4 selenium pyexecjs
需要下載對應版本的ChromeDriver:
from selenium import webdriver
driver = webdriver.Chrome(executable_path='./chromedriver')
訪問抖音網頁版(https://www.douyin.com/)可以發現: - 熱門視頻通過異步加載 - 數據接口有簽名驗證 - 視頻鏈接為動態生成
通過瀏覽器開發者工具(F12)抓包分析,找到核心數據接口:
https://www.douyin.com/aweme/v1/web/hot/search/list/
抖音采用了以下防護措施: 1. User-Agent驗證 2. 請求頻率限制 3. 參數簽名(_signature) 4. Cookie驗證
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Referer': 'https://www.douyin.com/'
}
def get_html(url):
try:
resp = requests.get(url, headers=headers)
resp.raise_for_status()
return resp.text
except Exception as e:
print(f"請求失敗: {e}")
return None
抖音接口需要_signature參數,可通過以下方式生成:
import execjs
def generate_signature(user_id):
with open('douyin.js', 'r', encoding='utf-8') as f:
js_code = f.read()
ctx = execjs.compile(js_code)
return ctx.call('get_sign', user_id)
需要配套的JavaScript文件(douyin.js)實現簽名算法。
當直接請求失敗時,可采用瀏覽器自動化方案:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
def selenium_crawl():
driver.get("https://www.douyin.com/")
wait = WebDriverWait(driver, 10)
# 等待視頻加載
videos = wait.until(
lambda d: d.find_elements(By.XPATH, '//div[@class="video-card"]')
)
for video in videos:
# 提取視頻信息...
from bs4 import BeautifulSoup
def parse_html(html):
soup = BeautifulSoup(html, 'lxml')
video_list = []
for item in soup.select('.video-feed-item'):
try:
video = {
'title': item.select_one('.title').text.strip(),
'author': item.select_one('.author-name').text,
'likes': item.select_one('.like-count').text,
'video_url': item.select_one('a')['href']
}
video_list.append(video)
except Exception as e:
print(f"解析異常: {e}")
return video_list
# douyin_spider.py
import json
from time import sleep
from urllib.parse import quote
class DouyinSpider:
def __init__(self):
self.base_url = "https://www.douyin.com"
self.api_url = "https://www.douyin.com/aweme/v1/web/hot/search/list/"
self.headers = {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
def get_hot_videos(self, max_count=50):
"""獲取熱門視頻"""
all_videos = []
params = {
'device_platform': 'web',
'count': 20,
'cursor': 0
}
while len(all_videos) < max_count:
params['cursor'] = len(all_videos)
params['_signature'] = generate_signature(params)
resp = requests.get(
self.api_url,
params=params,
headers=self.headers
)
if resp.status_code == 200:
data = resp.json()
all_videos.extend(data['aweme_list'])
sleep(2) # 禮貌性延遲
else:
print(f"請求失敗: {resp.status_code}")
break
return all_videos[:max_count]
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['douyin']
collection = db['hot_videos']
def save_to_mongo(data):
try:
collection.insert_many(data)
print(f"成功存儲{len(data)}條數據")
except Exception as e:
print(f"存儲失敗: {e}")
import csv
def save_to_csv(data, filename):
keys = data[0].keys()
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=keys)
writer.writeheader()
writer.writerows(data)
IP代理池:使用付費代理服務如Luminati
proxies = {
'http': 'http://user:pass@proxy_ip:port',
'https': 'https://user:pass@proxy_ip:port'
}
請求間隔隨機化
from random import uniform
sleep(uniform(1, 3))
User-Agent輪換
from fake_useragent import UserAgent
ua = UserAgent()
headers['User-Agent'] = ua.random
根據《網絡安全法》相關規定,未經授權抓取非公開數據可能涉及法律風險。
本文詳細介紹了從抖音網頁端獲取熱門視頻的完整技術方案。實際開發中還需要注意: - 抖音接口會定期更新,需要持續維護 - 建議使用官方API(如有權限) - 大數據量采集建議分布式爬蟲架構
完整項目代碼已上傳GitHub(示例倉庫地址)。如果對您有幫助,請給個Star支持!
”`
(注:實際文章需要補充更多技術細節和示意圖,此處為簡化版框架。字符統計:約1850字)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。