1. 程式人生 > 實用技巧 >只要30行程式碼!7步教會你Python爬取網頁抖音熱門視訊

只要30行程式碼!7步教會你Python爬取網頁抖音熱門視訊

前言

抖音短視訊相信大家都聽過,也不陌生對吧!可以看到海量的短視訊,涵蓋了各大行業。個人覺得抖音有毒,刷著刷著根本停不下來,一看時間就是凌晨3、4點。今天帶大家爬取抖音網頁版的視訊資料!一睹為快吧

本篇文章內容:

1、系統分析網頁性質

2、正則提取資料(難點)

3、海量音訊資料儲存

環境介紹:

python 3.6
pycharm
requests
re

爬蟲的一般思路

1、分析目標網頁,確定爬取的url路徑,headers引數

2、傳送請求 -- requests 模擬瀏覽器傳送請求,獲取響應資料

3、解析資料 -- 正則表示式

4、儲存資料 -- 儲存在目標資料夾中

步驟:

1、匯入工具

base_url = 'http://douyin.bm8.com.cn/d_1.html'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}

2、分析目標網頁,確定爬取的url路徑,headers引數

base_url = 'http://douyin.bm8.com.cn/d_1.html'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36
'}

3、傳送請求 -- requests 模擬瀏覽器傳送請求,獲取響應資料

response = requests.get(url=base_url, headers=headers)
html_data = response.text

4、解析資料 -- 正則表示式

pattern = re.compile('onclick="open1\(\'(.*?)\',\'(.*?)\',\'\'\)')
result = pattern.findall(html_data)
print(result)

5、構建一個for迴圈

for page in range(8, 10):
    
print('===================正在取第{}頁資料================='.format(page)) # 1、分析目標網頁,確定爬取的url路徑,headers引數 base_url = 'http://douyin.bm8.com.cn/d_{}.html'.format(page) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}

6、處理檔名非法字元

def change_title(title):
    pattern = re.compile(r"[\/\\\:\*\?\"\<\>\|]")  # '/ \ : * ? " < > |'
    new_title = re.sub(pattern, "_", title)  # 替換為下劃線
    return new_title

7、儲存資料 -- 儲存在目標資料夾中

for title, url in result:
        # 請求抖音視訊資料
        data = requests.get(url=url, headers=headers).content

        new_title = change_title(title)
        with open('videos\\' + new_title + '.mp4', mode='wb') as f:
            f.write(data)
            print('儲存完成:', title)