時間:2024-02-10 16:45:01 | 來源:網(wǎng)站運營
時間:2024-02-10 16:45:01 來源:網(wǎng)站運營
Python如何爬動態(tài)網(wǎng)頁,詳細(xì)教程,小菜鳥一個?:在之前的推文中,我們介紹了如何爬取一個簡單的靜態(tài)網(wǎng)站——「Python 爬取靜態(tài)網(wǎng)站:以歷史天氣為例」,但是在實際過程中,常常會遇到需要爬取動態(tài)網(wǎng)站數(shù)據(jù)的情況。在本文中,我們也將通過一個比較簡單的案例,來介紹爬取動態(tài)網(wǎng)站數(shù)據(jù)的基本思路和步驟。
bilibili
視頻評論為例,來具體介紹如何通過 Python 爬取動態(tài)網(wǎng)頁的數(shù)據(jù)。主要內(nèi)容包括:json
格式數(shù)據(jù); 如何把數(shù)據(jù)實時存入 csv
文件; 如何循環(huán)爬取多頁數(shù)據(jù)。# 導(dǎo)入模塊import requestsimport time# 網(wǎng)址url = "https://api.bilibili.com/x/v2/reply/main" # 接口網(wǎng)址的主要結(jié)構(gòu)# 請求頭數(shù)據(jù)headers = { 'accept': '*/*', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8', 'referer': 'https://www.bilibili.com/video/BV16X4y1g7wT', 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': 'Windows', 'sec-fetch-dest': 'script', 'sec-fetch-mode': 'no-cors', 'sec-fetch-site': 'same-site', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36' # 根據(jù)測試不需要 cookie 信息也可以獲取數(shù)據(jù) # 需要 cookie 的話在自己的瀏覽器中復(fù)制,這里涉及隱私就不放 cookie 信息了}# 構(gòu)造請求參數(shù)params = { # 'callback': 'jQuery17201888299578386794_' + str(round(time.time() * 1000)), # 'jsonp': 'jsonp', 'next': 0, # 頁碼 'type': 1, 'oid': 715024588, # 視頻av號 # 'mode': 3, # 評論排序方式 # 'plat': 1, # '_': str(round(time.time() * 1000)) # 生成當(dāng)前時間戳}# 通過get方法請求數(shù)據(jù)response = requests.get(url, headers=headers, params=params)
查看返回結(jié)果,<Response [200]> 代表請求數(shù)據(jù)成功。如果是 403 或 404 則說明請求不成功,可能需要檢查電腦網(wǎng)絡(luò)是否通暢、目標(biāo)網(wǎng)址是否可以正常訪問、headers
是否有正確設(shè)置等。json
格式存儲的,而每條評論的數(shù)據(jù)在 data
下面的replies
中。# 導(dǎo)入模塊import jsonimport timeresponse.encoding = 'utf-8' # 修改編碼格式data_json = json.loads(response.text) # 通過 json 解析數(shù)據(jù)comment_list = data_json['data']['replies'] # 獲取 data 下面的 replies 列表comments = [] # 構(gòu)建空列表保存每頁的評論數(shù)據(jù)for i in range(len(comment_list)): # 循環(huán)獲取每條評論的數(shù)據(jù) comment = { 'id': comment_list[i]['rpid'], # 評論id # 評論時間,由時間戳轉(zhuǎn)換 'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(comment_list[i]['ctime'])), 'parent': comment_list[i]['parent'], # 父評論id 'like': comment_list[i]['like'], # 點贊數(shù) 'user_id': comment_list[i]['member']['mid'], # 評論用戶id 'user_name': comment_list[i]['member']['uname'], # 用戶名 'content': comment_list[i]['content']['message'] # 評論內(nèi)容 # 需要其他數(shù)據(jù)的可以再在 json 中查看并獲取對應(yīng)的名稱 } comments.append(comment) # 每頁的評論數(shù)據(jù)
# 導(dǎo)入模塊import csv# 保存數(shù)據(jù)的文件路徑save_path = 'bilibili.csv'# 將數(shù)據(jù)寫入 csv with open(save_path, 'a', newline='', encoding='utf-8') as fp: csv_header = ['id', 'time', 'parent', 'like', 'user_id', 'user_name', 'content'] # 設(shè)置表頭,即列名 csv_writer = csv.DictWriter(fp, csv_header) # 如果文件不存在,則寫入表頭;如果文件已經(jīng)存在,則直接追加數(shù)據(jù)不再次寫入表頭 if fp.tell() == 0: csv_writer.writeheader() csv_writer.writerows(comments) # 寫入數(shù)據(jù)
# -*- coding: utf-8 -*-# Author: W.Y.# Email: wangyingchn@outlook.com# Date: 2022/4/12# 導(dǎo)入模塊import requests # 請求數(shù)據(jù)import time # 時間模塊import json # json 模塊,儲存數(shù)據(jù)import csv # 保存數(shù)據(jù)# 請求數(shù)據(jù)def get_response(page): url = 'https://api.bilibili.com/x/v2/reply/main' # 接口網(wǎng)址的主要結(jié)構(gòu) # 請求頭數(shù)據(jù) headers = { 'accept': '*/*', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8', 'referer': 'https://www.bilibili.com/video/BV16X4y1g7wT', 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': 'Windows', 'sec-fetch-dest': 'script', 'sec-fetch-mode': 'no-cors', 'sec-fetch-site': 'same-site', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36' # 根據(jù)測試不需要 cookie 信息也可以獲取數(shù)據(jù) # 需要 cookie 的話在自己的瀏覽器中復(fù)制,這里涉及隱私就不放 cookie 信息了 } # 構(gòu)造請求參數(shù) params = { # 'callback': 'jQuery17201888299578386794_' + str(round(time.time() * 1000)), # 'jsonp': 'jsonp', 'next': page, # 頁碼 'type': 1, 'oid': 715024588, # 視頻av號 'mode': 3, # 評論排序方式 # 'plat': 1, # '_': str(round(time.time() * 1000)) # 生成當(dāng)前時間戳 } # 通過get方法請求數(shù)據(jù) response = requests.get(url, headers=headers, params=params) return response# 解析數(shù)據(jù)def parse_data(response): response.encoding = 'utf-8' # 修改編碼格式 data_json = json.loads(response.text) # 通過 json 解析數(shù)據(jù) comment_list = data_json['data']['replies'] # 獲取 data 下面的 replies 列表 comments = [] # 構(gòu)建空列表保存每頁的評論數(shù)據(jù) for i in range(len(comment_list)): # 循環(huán)獲取每條評論的數(shù)據(jù) comment = { 'id': comment_list[i]['rpid'], # 評論id 'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(comment_list[i]['ctime'])), # 評論時間,由時間戳轉(zhuǎn)換 'parent': comment_list[i]['parent'], # 父評論id 'like': comment_list[i]['like'], # 點贊數(shù) 'user_id': comment_list[i]['member']['mid'], # 評論用戶id 'user_name': comment_list[i]['member']['uname'], # 用戶名 'content': comment_list[i]['content']['message'] # 評論內(nèi)容 # 需要其他數(shù)據(jù)的可以再在 json 中查看并獲取對應(yīng)的名稱 } comments.append(comment) # 每頁的評論數(shù)據(jù) return comments# 保存數(shù)據(jù)def save_data(comments, save_path): with open(save_path, 'a', newline='', encoding='utf-8') as fp: # 設(shè)置表頭,即列名 csv_header = ['id', 'time', 'parent', 'like', 'user_id', 'user_name', 'content'] csv_writer = csv.DictWriter(fp, csv_header) # 如果文件不存在,則寫入表頭;如果文件已經(jīng)存在,則直接追加數(shù)據(jù)不再次寫入表頭 if fp.tell() == 0: csv_writer.writeheader() csv_writer.writerows(comments) # 寫入數(shù)據(jù)# 定義爬取函數(shù)def crawler(page, save_path): time.sleep(2) # 暫停 2 秒,避免請求過于頻繁 response = get_response(page) # 請求數(shù)據(jù) comments = parse_data(response) # 解析數(shù)據(jù) save_data(comments, save_path) # 儲存數(shù)據(jù) print(f'成功爬取第{page+1}頁')if __name__ == '__main__': save_file = 'bilibili.csv' # 保存路徑 total_counts = 1000 # 爬取 1000 條評論 # 如果要爬取所有評論,可以改成全部評論數(shù)。 # 如果要爬取多個視頻的評論,可以通過下面的代碼,爬取第一頁的時候返回所有的評論數(shù) # total_counts = data_json['data']['cursor']['all_count'] # 頁碼循環(huán),每頁有 20 條評論,所以通過總評論數(shù)計算頁碼 for p in range(total_counts//20 + 1): crawler(p, save_file)
詳細(xì)內(nèi)容參見連享會推文Note:產(chǎn)生如下推文列表的 Stata 命令為:. lianxh Python
. songbl Python
安裝最新版lianxh
/songbl
命令:. ssc install lianxh, replace
. ssc install songbl, replace
關(guān)鍵詞:教程,詳細(xì),動態(tài),小菜
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。