一、背景介紹
1.1 爬取目標
熟悉我的小伙伴都了解,我之前開發過2款軟件:
【GUI軟件】小紅書搜索結果批量采集,支持多個關鍵詞同時抓取!
【GUI軟件】小紅書詳情數據批量采集,含筆記內容、轉評贊藏等,支持多筆記同時采集!
現在介紹的這個軟件,相當于以上2個軟件的結合版,即根據關鍵詞爬取筆記的詳情數據。
開發界面軟件的目的:方便不懂編程代碼的小白用戶使用,無需安裝python,無需改代碼,雙擊打開即用!
軟件界面截圖:
爬取結果截圖:
結果截圖1:
結果截圖2:
結果截圖3:
以上。
1.2 演示視頻
軟件使用演示:(不懂編程的小白直接看視頻,了解軟件作用即可,無需看代碼)
【軟件演示】爬小紅書搜索詳情軟件
1.3 軟件說明
幾點重要說明:
以上。
二、代碼講解
2.1 爬蟲采集-搜索接口
首先,定義接口地址作為請求地址:
# 請求地址
url = 'https://edith.xiaohongshu.com/api/sns/web/v1/search/notes'
定義一個請求頭,用于偽造瀏覽器:
# 請求頭
h1 = {'Accept': 'application/json, text/plain, */*','Accept-Encoding': 'gzip, deflate, br','Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6','Content-Type': 'application/json;charset=UTF-8','Cookie': '換成自己的cookie值','Origin': 'https://www.xiaohongshu.com','Referer': 'https://www.xiaohongshu.com/','Sec-Ch-Ua': '"Microsoft Edge";v="119", "Chromium";v="119", "Not?A_Brand";v="24"','Sec-Ch-Ua-Mobile': '?0','Sec-Ch-Ua-Platform': '"macOS"','Sec-Fetch-Dest': 'empty','Sec-Fetch-Mode': 'cors','Sec-Fetch-Site': 'same-site','User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',
}
加上請求參數,告訴程序你的爬取條件是什么:
# 請求參數
post_data = {"keyword": search_keyword,"page": page,"page_size": 20,"search_id": v_search_id,"sort": v_sort,"note_type": v_note_type,"image_scenes": "FD_PRV_WEBP,FD_WM_WEBP",
}
2.2 爬蟲采集-詳情接口
首先,定義接口地址作為請求地址:
# 請求地址
url = 'https://edith.xiaohongshu.com/api/sns/web/v1/feed'
定義一個請求頭,用于偽造瀏覽器:
# 請求頭
h1 = {'Accept': 'application/json, text/plain, */*','Accept-Encoding': 'gzip, deflate, br','Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6','Content-Type': 'application/json;charset=UTF-8','Cookie': '換成自己的cookie值','Origin': 'https://www.xiaohongshu.com','Referer': 'https://www.xiaohongshu.com/','Sec-Ch-Ua': '"Microsoft Edge";v="119", "Chromium";v="119", "Not?A_Brand";v="24"','Sec-Ch-Ua-Mobile': '?0','Sec-Ch-Ua-Platform': '"macOS"','Sec-Fetch-Dest': 'empty','Sec-Fetch-Mode': 'cors','Sec-Fetch-Site': 'same-site','User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',
}
加上請求參數,告訴程序你的爬取條件是什么:
# 請求參數
post_data = {"source_note_id": note_id,"image_formats": ["jpg", "webp", "avif"],"extra": {"need_body_topic": "1"}
}
下面就是發送請求和接收數據:
# 發送請求
r = requests.post(url, headers=h1, data=data_json)
# 接收數據
json_data = r.json()
逐個解析字段數據,以"筆記標題"為例:
# 筆記標題
try:title = json_data['data']['items'][0]['note_card']['title']
except:title = ''
熟悉xhs的朋友都知道,有些筆記是沒有標題的,所以這里加上try保護,防止程序報錯導致中斷運行。
其他字段同理,不再贅述。
下面就是發送請求和接收數據:
# 發送請求
r = requests.post(url, headers=h1, data=data_json.encode('utf8'))
print(r.status_code)
# 以json格式接收返回數據
json_data = r.json()
定義一些空列表,用于存放解析后字段數據:
# 定義空列表
note_id_list = [] # 筆記id
note_title_list = [] # 筆記標題
note_type_list = [] # 筆記類型
like_count_list = [] # 點贊數
user_id_list = [] # 用戶id
user_name_list = [] # 用戶昵稱
循環解析字段數據,以"筆記標題"為例:
# 循環解析
for data in json_data['data']['items']:# 筆記標題try:note_title = data['note_card']['display_title']except:note_title = ''print('note_title:', note_title)note_title_list.append(note_title)
其他字段同理,不再贅述。
最后,是把數據保存到csv文件:
# 把數據保存到Dataframe
df = pd.DataFrame({'關鍵詞': search_keyword,'頁碼': page,'筆記id': note_id_list,'筆記鏈接': ['https://www.xiaohongshu.com/explore/' + i for i in note_id_list],'筆記標題': note_title_list,'筆記類型': note_type_list,'點贊數': like_count_list,'用戶id': user_id_list,'用戶主頁鏈接': ['https://www.xiaohongshu.com/user/profile/' + i for i in user_id_list],'用戶昵稱': user_name_list,}
)
if os.path.exists(result_file):header = False
else:header = True
# 把數據保存到csv文件
df.to_csv(result_file, mode='a+', index=False, header=header, encoding='utf_8_sig')
完整代碼中,還含有:判斷循環結束條件、js逆向解密、筆記類型(綜合/視頻圖文)篩選、排序方式篩選(綜合/最新/最熱)等關鍵實現邏輯。
2.3 cookie說明
其中,cookie是個關鍵參數。
cookie里的a1和web_session獲取方法,如下:
這兩個值非常重要,軟件界面需要填寫!!
開發者模式的打開方法:頁面空白處->右鍵->檢查。
2.4 軟件界面模塊
主窗口部分:
# 創建主窗口
root = tk.Tk()
root.title('小紅書搜索詳情采集軟件v1.0 | 馬哥python說 |')
# 設置窗口大小
root.minsize(width=850, height=650)
輸入控件部分:
# 搜索關鍵詞
tk.Label(root, justify='left', text='搜索關鍵詞:').place(x=30, y=160)
entry_kw = tk.Text(root, bg='#ffffff', width=60, height=2, )
entry_kw.place(x=125, y=160, anchor='nw') # 擺放位置
底部版權部分:
# 版權信息
copyright = tk.Label(root, text='@馬哥python說 All rights reserved.', font=('仿宋', 10), fg='grey')
copyright.place(x=290, y=625)
以上。
2.5 日志模塊
好的日志功能,方便軟件運行出問題后快速定位原因,修復bug。
核心代碼:
def get_logger(self):self.logger = logging.getLogger(__name__)# 日志格式formatter = '[%(asctime)s-%(filename)s][%(funcName)s-%(lineno)d]--%(message)s'# 日志級別self.logger.setLevel(logging.DEBUG)# 控制臺日志sh = logging.StreamHandler()log_formatter = logging.Formatter(formatter, datefmt='%Y-%m-%d %H:%M:%S')# info日志文件名info_file_name = time.strftime("%Y-%m-%d") + '.log'# 將其保存到特定目錄,ap方法就是尋找項目根目錄,該方法博主前期已經寫好。case_dir = r'./logs/'info_handler = TimedRotatingFileHandler(filename=case_dir + info_file_name,when='MIDNIGHT',interval=1,backupCount=7,encoding='utf-8')
日志文件截圖:
以上。
三、獲取源碼及軟件
完整python源碼及exe軟件,微信公眾號"老男孩的平凡之路“后臺回復”爬小紅書搜索詳情軟件"即可獲取。點擊直達