1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
| import requests import re import json import time import csv
def get_header(): header = {} with open("./xhs_cookie.txt") as f: header["Cookie"] = f.read() header['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0' header['Referer'] = "https://www.xiaohongshu.com/" header['x-s'] = 'XYS_2UQhPsHCH0c1Pjh9HjIj2erjwjQhyoPTqBPT49pjHjIj2eHjwjQgynEDJ74AHjIj2ePjwjQTJdPIP/ZlgMrU4SmH4B4kP9qE2eYitMStyA48p7m/aBII2fSTJLRfcD8g+BEwPFE9pe4bJLQNJfTaLgmznn+TydmLaMYf4A46peziLgLEp9M9/7mOar+/+rp1/FR9GSQI+pQY8LSa2g4a2dmftA+yJLTe8/QY+BSy+D8zLp4MJMzLpri7z9lBJrEj+rEgJnWM2rqEJFQbcSzEwrl8zebFaokCLFiEyeYH8dz6P9Rx2LP9HjIj2ecjwjHjKc==' header['x-s-common'] = '2UQAPsHC+aIjqArjwjHjNsQhPsHCH0rjNsQhPaHCH0c1Pjh9HjIj2eHjwjQgynEDJ74AHjIj2ePjwjQ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+APgp74LksngbQyrD3a/PMqM8P+fp3JDkS8oPA8/mn49bQzLM3aL+QLB+n494QP7bbagYd8gYytA8N8jRSngp7+DDApAGhpdqUJLHM8n8m8o+/LozUqobFPDSk//SQyBYc/opF4sTc4FkQyLES8Blwq9TM47zALozsanVFJaHVHdWEH0iU+0GUPer7+eZVHdWlPsHCPsIj2erlH0ijJfRUJnbVHdF=' return header
def get_user(user_id, xsec_token): try: user_url = f'https://www.xiaohongshu.com/user/profile/{user_id}?xsec_token={xsec_token}&xsec_source=pc_comment' resp = requests.get(url=user_url, headers=get_header(), timeout=10) resp.raise_for_status() data_text = resp.content.decode('utf-8') matched = re.findall(r'<script>(.+?)</script>', data_text) if not matched: return '', '', '', '', '', '', '', '', '' user_data = json.loads( matched[-1].replace('window.__INITIAL_STATE__=', '').replace("undefined", "null") )['user']
basic_info = user_data.get('userPageData', {}).get('basicInfo', {}) interactions = user_data.get('userPageData', {}).get('interactions', []) notes = user_data.get('notes', [])
ipLocation = basic_info.get('ipLocation', '') desc = basic_info.get('desc', '') gender_code = basic_info.get('gender') if gender_code == 0: gender = "男" elif gender_code == 1: gender = "女" else: gender = '' age = '' constellation = '' for tag in user_data.get('userPageData', {}).get('tags', []): tag_name = tag.get('name', '') if "岁" in tag_name: age = tag_name elif "座" in tag_name: constellation = tag_name
follows = interactions[0].get('count') if len(interactions) > 0 else '' fans = interactions[1].get('count') if len(interactions) > 1 else '' interaction = interactions[2].get('count') if len(interactions) > 2 else ''
notes_counts = len(notes[0]) if notes else 0 if notes_counts >= 30: notes_counts = "30+"
return gender, age, constellation, ipLocation, desc, follows, fans, interaction, notes_counts
except Exception as e: print(f"[用户信息获取失败] user_id={user_id}, 错误: {e}") return '', '', '', '', '', '', '', '', ''
def get_json_data(comment, writer, counter, is_fast=False): user_id = comment.get('user_info', {}).get('user_id', '') user_xsec_token = comment.get('user_info', {}).get('xsec_token', '') nickname = comment.get('user_info', {}).get('nickname', '') content = comment.get('content', '') create_time = comment.get('create_time', 0) / 1000 create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(create_time)) if create_time else '' ip_location = comment.get('ip_location', '') like_count = comment.get('like_count', 0) sub_comment_count = comment.get('sub_comment_count',0) if is_fast: row = [ user_id, nickname, create_time, ip_location, content, like_count, sub_comment_count ] else: gender, age, constellation, ipLocation, desc, follows, fans, interaction, notes_counts = get_user(user_id, user_xsec_token) row = [ user_id, nickname, gender, age, constellation, create_time, ipLocation, ip_location, content, like_count, sub_comment_count, desc, follows, fans, interaction, notes_counts ]
writer.writerow(row) counter[0] += 1 print(counter) pause_interval = 50 if is_fast else 10 if counter[0] % pause_interval == 0: print(f"已经爬取{counter[0]}条数据,暂停5秒....") time.sleep(5) return writer, counter
def get_sub_data(note_id, root_comment_id, sub_cursor, xsec_token, writer, counter, is_fast=False): sub_url = f"https://edith.xiaohongshu.com/api/sns/web/v2/comment/sub/page?note_id={note_id}&root_comment_id={root_comment_id}&num=10&cursor={sub_cursor}&image_formats=jpg,webp,avif&top_comment_id=&xsec_token={xsec_token}" resp = requests.get(url=sub_url, headers=get_header(), timeout=10) resp.raise_for_status() xhs_data = json.loads(resp.content.decode('utf-8')).get('data', {}) for sub_comment in xhs_data.get('comments', [])[1:]: writer, counter = get_json_data(sub_comment, writer, counter, is_fast)
has_more = xhs_data.get('has_more',False) while has_more: sub_cursor = xhs_data.get('cursor','') sub_url = f"https://edith.xiaohongshu.com/api/sns/web/v2/comment/sub/page?note_id={note_id}&root_comment_id={root_comment_id}&num=10&cursor={sub_cursor}&image_formats=jpg,webp,avif&top_comment_id=&xsec_token={xsec_token}" resp = requests.get(url=sub_url, headers=get_header(), timeout=10) resp.raise_for_status() xhs_data = json.loads(resp.content.decode('utf-8')).get('data', {}) for sub_comment in xhs_data.get('comments', []): writer, counter = get_json_data(sub_comment, writer, counter, is_fast) has_more = xhs_data.get('has_more',False)
return writer,counter
def get_data(is_sub, note_id, xsec_token, cursor, top_comment_id, writer, counter, is_fast=False): try: comments_url = f'https://edith.xiaohongshu.com/api/sns/web/v2/comment/page?note_id={note_id}&cursor={cursor}&top_comment_id={top_comment_id}&image_formats=jpg,webp,avif&xsec_token={xsec_token}' resp = requests.get(url=comments_url, headers=get_header(), timeout=10) resp.raise_for_status() xhs_data = json.loads(resp.content.decode('utf-8')).get('data', {}) except Exception as e: print(f"[评论获取失败] cursor={cursor}, 错误: {e}") return
for comment in xhs_data.get('comments', []):
writer, counter = get_json_data(comment, writer, counter, is_fast) if is_sub == True: sub_comments = comment.get('sub_comments',[]) if len(sub_comments) == 1: writer, counter = get_json_data(sub_comments[0], writer, counter, is_fast) sub_comment_has_more = comment.get('sub_comment_has_more',False) if sub_comment_has_more: root_comment_id = sub_comments[0].get('target_comment','').get("id",'') sub_cursor = sub_comments[0].get("cursor",'') writer, counter = get_sub_data(note_id, root_comment_id, sub_cursor, xsec_token, writer, counter, is_fast)
if xhs_data.get('has_more'): cursor = xhs_data.get('cursor', '') get_data(is_sub, note_id, xsec_token, cursor, top_comment_id, writer, counter, is_fast) else: print(f"爬取结束!共获取 {counter[0]} 条评论。")
if __name__ == "__main__": is_sub = True mode = 'fast' is_fast = (mode == 'fast') xhs_url = 'https://www.xiaohongshu.com/explore/6a6f21860000000028000eb7?xsec_token=ABqYNBN1lX0C8NAJSb0frM2WTBarTD9PKqwHaBHBesMmI=&xsec_source=pc_feed' note_id = re.findall(r"/explore/(.+?)\?", xhs_url)[0] xsec_token = re.findall(r"xsec_token=(.+?)&", xhs_url)[0] cursor = '' top_comment_id = '' title = re.findall(r'<title>(.+?) - 小红书</title>',requests.get(url=xhs_url,headers=get_header()).content.decode('utf-8'))[0] if is_sub == True: title = title + "(二级评论)" else: title = title + "(一级评论)" if is_fast: title = title + "(极速版)"
with open(f'{title}.csv', "w", newline="", encoding="utf-8-sig") as f: writer = csv.writer(f) fast_header = ["用户ID", "用户名", "发表日期", "评论IP", "评论内容", "点赞数量", "回复数量"] rich_header = ["用户ID", "用户名", "性别", "年龄", "星座", "发表日期", "主页IP", "评论IP", "评论内容", "点赞数量", "回复数量", "用户简介", "关注", "粉丝", "获赞与收藏", "笔记数量"] writer.writerow(fast_header if is_fast else rich_header) counter = [0] get_data(is_sub, note_id, xsec_token, cursor, top_comment_id, writer, counter, is_fast)
|