|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Copyright (c) 2025 relakkes@gmail.com |
| 3 | +# |
| 4 | +# This file is part of MediaCrawler project. |
| 5 | +# Repository: https://github.com/NanmiCoder/MediaCrawler/blob/main/tests/test_xhs_note_url_parse.py |
| 6 | +# GitHub: https://github.com/NanmiCoder |
| 7 | +# Licensed under NON-COMMERCIAL LEARNING LICENSE 1.1 |
| 8 | +# |
| 9 | +# 声明:本代码仅供学习和研究目的使用。使用者应遵守以下原则: |
| 10 | +# 1. 不得用于任何商业用途。 |
| 11 | +# 2. 使用时应遵守目标平台的使用条款和robots.txt规则。 |
| 12 | +# 3. 不得进行大规模爬取或对平台造成运营干扰。 |
| 13 | +# 4. 应合理控制请求频率,避免给目标平台带来不必要的负担。 |
| 14 | +# 5. 不得用于任何非法或不当的用途。 |
| 15 | +# |
| 16 | +# 详细许可条款请参阅项目根目录下的LICENSE文件。 |
| 17 | +# 使用本代码即表示您同意遵守上述原则和LICENSE中的所有条款。 |
| 18 | + |
| 19 | +"""小红书笔记链接解析的回归测试。 |
| 20 | +
|
| 21 | +``parse_note_info_from_note_url`` 过去用 ``url.split("/")[-1].split("?")[0]`` |
| 22 | +取笔记 ID:链接在 ID 后面多一个斜杠(``/explore/<id>/?xsec_token=...``)时 |
| 23 | +取到的是空字符串,带 ``#`` 锚点时 ID 会带上锚点内容。 |
| 24 | +
|
| 25 | +这里只测纯函数,不发网络请求。 |
| 26 | +""" |
| 27 | + |
| 28 | +from __future__ import annotations |
| 29 | + |
| 30 | +import pytest |
| 31 | + |
| 32 | +from media_platform.xhs.help import parse_note_info_from_note_url |
| 33 | + |
| 34 | +NOTE_ID = "66fad51c000000001b0224b8" |
| 35 | +TOKEN = "AB3rO-QopW5sgrJ41GwN01WCXh6yWPxjSoFI9D5JIMgKw=" |
| 36 | + |
| 37 | + |
| 38 | +@pytest.mark.parametrize( |
| 39 | + "url", |
| 40 | + [ |
| 41 | + f"https://www.xiaohongshu.com/explore/{NOTE_ID}?xsec_token={TOKEN}&xsec_source=pc_search", |
| 42 | + f"https://www.xiaohongshu.com/explore/{NOTE_ID}/?xsec_token={TOKEN}&xsec_source=pc_search", |
| 43 | + f"https://www.xiaohongshu.com/explore/{NOTE_ID}/", |
| 44 | + f"https://www.xiaohongshu.com/explore/{NOTE_ID}", |
| 45 | + f"https://www.xiaohongshu.com/discovery/item/{NOTE_ID}?xsec_token={TOKEN}&xsec_source=pc_search#comments", |
| 46 | + f"https://www.xiaohongshu.com/discovery/item/{NOTE_ID}#comments", |
| 47 | + ], |
| 48 | +) |
| 49 | +def test_note_id_is_parsed(url): |
| 50 | + assert parse_note_info_from_note_url(url).note_id == NOTE_ID |
| 51 | + |
| 52 | + |
| 53 | +def test_query_params_still_parsed_with_trailing_slash(): |
| 54 | + info = parse_note_info_from_note_url( |
| 55 | + f"https://www.xiaohongshu.com/explore/{NOTE_ID}/?xsec_token={TOKEN}&xsec_source=pc_search" |
| 56 | + ) |
| 57 | + |
| 58 | + assert info.xsec_token == TOKEN |
| 59 | + assert info.xsec_source == "pc_search" |
0 commit comments