宅男在线永久免费观看网直播,亚洲欧洲日产国码无码久久99,野花社区在线观看视频,亚洲人交乣女bbw,一本一本久久a久久精品综合不卡

全部
常見問題
產(chǎn)品動(dòng)態(tài)
精選推薦

如何使用Python通過API接口批量抓取小紅書筆記評(píng)論?

管理 管理 編輯 刪除

一、技術(shù)可行性分析

  1. API存在性驗(yàn)證 小紅書官方未公開評(píng)論API,需通過逆向工程獲取接口 典型評(píng)論接口特征:參考小紅書開放平臺(tái)API接口
  2. 請(qǐng)求參數(shù)解析 csharp 體驗(yàn)AI代碼助手 代碼解讀復(fù)制代碼python # 典型請(qǐng)求參數(shù)示例 params = { "note_id": "64a1b2c3d4e5f6g7h8i9j0k1", # 筆記ID "sort": "newest", # 排序方式 "page": 1, # 頁(yè)碼 "page_size": 20 # 每頁(yè)數(shù)量 }

二、完整技術(shù)實(shí)現(xiàn)方案

python
import requests
import json
import time
from urllib.parse import urlencode
 
class XiaohongshuCommentScraper:
    def __init__(self):
        self.session = requests.Session()
        self.headers = {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
            "X-Request-ID": "api.comment_list",
            "Content-Type": "application/json"
        }
        self.base_url = "https://www.xiaohongshu.com/api/sns/note/v1/comment_list"
 
    def get_comments(self, note_id, max_pages=5):
        comments = []
        for page in range(1, max_pages+1):
            params = {
                "note_id": note_id,
                "sort": "newest",
                "page": page,
                "page_size": 20
            }
            
            try:
                response = self.session.get(
                    self.base_url, 
                    headers=self.headers,
                    params=urlencode(params)
                )
                data = response.json()
                
                if data.get('errcode') != 0:
                    raise Exception(f"API Error: {data.get('errmsg')}")
                
                page_comments = data.get('data', {}).get('comments', [])
                if not page_comments:
                    break
                    
                comments.extend([{
                    "id": c["id"],
                    "user": c["user"]["nickname"],
                    "content": c["content"],
                    "like_count": c["like_count"],
                    "create_time": c["create_time"]
                } for c in page_comments])
                
                time.sleep(1.5)  # 反爬延遲
                
            except Exception as e:
                print(f"Error on page {page}: {str(e)}")
                break
                
        return comments
 
if __name__ == "__main__":
    scraper = XiaohongshuCommentScraper()
    note_id = "64a1b2c3d4e5f6g7h8i9j0k1"  # 替換為實(shí)際筆記ID
    
    comments = scraper.get_comments(note_id, max_pages=3)
    print(f"成功抓取 {len(comments)} 條評(píng)論")
    
    # 保存為CSV文件
    with open("comments.csv", "w", encoding="utf-8") as f:
        f.write("ID,用戶,內(nèi)容,點(diǎn)贊數(shù),創(chuàng)建時(shí)間\n")
        for c in comments:
            f.write(f"{c['id']},{c['user']},{c['content']},{c['like_count']},{c['create_time']}\n")

三、進(jìn)階優(yōu)化方案

  1. 分布式爬取架構(gòu) python 體驗(yàn)AI代碼助手 代碼解讀復(fù)制代碼python from concurrent.futures import ThreadPoolExecutor def distributed_scraping(note_ids): with ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(scraper.get_comments, nid, 2) for nid in note_ids] results = [f.result() for f in futures] return results
  2. 反爬對(duì)抗策略 ruby 體驗(yàn)AI代碼助手 代碼解讀復(fù)制代碼python class AntiCrawler: @staticmethod def get_proxy(): # 返回可用代理IP return {"http": "123.45.67.89:8080"} @staticmethod def random_delay(): time.sleep(random.uniform(1, 3))

四、數(shù)據(jù)存儲(chǔ)擴(kuò)展

python
import sqlite3
 
class DataStorage:
    def __init__(self):
        self.conn = sqlite3.connect("comments.db")
        self._create_table()
        
    def _create_table(self):
        cursor = self.conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS comments (
                id TEXT PRIMARY KEY,
                note_id TEXT,
                user TEXT,
                content TEXT,
                like_count INTEGER,
                create_time INTEGER
            )
        ''')
        self.conn.commit()
        
    def save_comments(self, comments, note_id):
        cursor = self.conn.cursor()
        for c in comments:
            cursor.execute('''
                INSERT OR REPLACE INTO comments 
                VALUES (?, ?, ?, ?, ?, ?)
            ''', (c["id"], note_id, c["user"], c["content"], c["like_count"], c["create_time"]))
        self.conn.commit()

五、法律與道德規(guī)范

  1. 遵守《網(wǎng)絡(luò)安全法》和《數(shù)據(jù)安全法》
  2. 禁止抓取用戶隱私信息(手機(jī)號(hào)、地址等)
  3. 控制請(qǐng)求頻率(建議QPS≤2)
  4. 明確標(biāo)注數(shù)據(jù)來源,禁止商業(yè)用途

該方案通過模擬移動(dòng)端請(qǐng)求實(shí)現(xiàn)評(píng)論抓取,采用分頁(yè)機(jī)制和動(dòng)態(tài)延遲策略規(guī)避反爬限制。實(shí)際部署時(shí)建議配合代理IP池和異常重試機(jī)制,確保數(shù)據(jù)采集的穩(wěn)定性和合規(guī)性。


請(qǐng)登錄后查看

OneLafite 最后編輯于2025-07-08 14:49:15

快捷回復(fù)
回復(fù)
回復(fù)
回復(fù)({{post_count}}) {{!is_user ? '我的回復(fù)' :'全部回復(fù)'}}
排序 默認(rèn)正序 回復(fù)倒序 點(diǎn)贊倒序

{{item.user_info.nickname ? item.user_info.nickname : item.user_name}} LV.{{ item.user_info.bbs_level || item.bbs_level }}

作者 管理員 企業(yè)

{{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest == 1? '取消推薦': '推薦'}}
{{item.is_suggest == 1? '取消推薦': '推薦'}}
沙發(fā) 板凳 地板 {{item.floor}}#
{{item.user_info.title || '暫無簡(jiǎn)介'}}
附件

{{itemf.name}}

{{item.created_at}}  {{item.ip_address}}
打賞
已打賞¥{{item.reward_price}}
{{item.like_count}}
{{item.showReply ? '取消回復(fù)' : '回復(fù)'}}
刪除
回復(fù)
回復(fù)

{{itemc.user_info.nickname}}

{{itemc.user_name}}

回復(fù) {{itemc.comment_user_info.nickname}}

附件

{{itemf.name}}

{{itemc.created_at}}
打賞
已打賞¥{{itemc.reward_price}}
{{itemc.like_count}}
{{itemc.showReply ? '取消回復(fù)' : '回復(fù)'}}
刪除
回復(fù)
回復(fù)
查看更多
打賞
已打賞¥{{reward_price}}
82
{{like_count}}
{{collect_count}}
添加回復(fù) ({{post_count}})

相關(guān)推薦

快速安全登錄

使用微信掃碼登錄
{{item.label}} 加精
{{item.label}} {{item.label}} 板塊推薦 常見問題 產(chǎn)品動(dòng)態(tài) 精選推薦 首頁(yè)頭條 首頁(yè)動(dòng)態(tài) 首頁(yè)推薦
取 消 確 定
回復(fù)
回復(fù)
問題:
問題自動(dòng)獲取的帖子內(nèi)容,不準(zhǔn)確時(shí)需要手動(dòng)修改. [獲取答案]
答案:
提交
bug 需求 取 消 確 定
打賞金額
當(dāng)前余額:¥{{rewardUserInfo.reward_price}}
{{item.price}}元
請(qǐng)輸入 0.1-{{reward_max_price}} 范圍內(nèi)的數(shù)值
打賞成功
¥{{price}}
完成 確認(rèn)打賞

微信登錄/注冊(cè)

切換手機(jī)號(hào)登錄

{{ bind_phone ? '綁定手機(jī)' : '手機(jī)登錄'}}

{{codeText}}
切換微信登錄/注冊(cè)
暫不綁定
CRMEB客服

CRMEB咨詢熱線 咨詢熱線

400-8888-794

微信掃碼咨詢

CRMEB開源商城下載 源碼下載 CRMEB幫助文檔 幫助文檔
返回頂部 返回頂部
CRMEB客服