unitbytes 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- unitbytes/__init__.py +43 -0
- unitbytes/_exceptions.py +94 -0
- unitbytes/_serialization.py +272 -0
- unitbytes/_transports.py +1529 -0
- unitbytes/ai.py +938 -0
- unitbytes/ali1688.py +538 -0
- unitbytes/alibaba.py +211 -0
- unitbytes/cli.py +454 -0
- unitbytes/client.py +124 -0
- unitbytes/gmaps.py +339 -0
- unitbytes/goofish.py +566 -0
- unitbytes/jobs.py +869 -0
- unitbytes/news.py +491 -0
- unitbytes/py.typed +1 -0
- unitbytes/reddit.py +342 -0
- unitbytes/rednote.py +286 -0
- unitbytes/request.py +7 -0
- unitbytes/shopping.py +644 -0
- unitbytes/travel.py +878 -0
- unitbytes/trends.py +1275 -0
- unitbytes-1.0.0.dist-info/METADATA +238 -0
- unitbytes-1.0.0.dist-info/RECORD +26 -0
- unitbytes-1.0.0.dist-info/WHEEL +5 -0
- unitbytes-1.0.0.dist-info/entry_points.txt +2 -0
- unitbytes-1.0.0.dist-info/licenses/LICENSE +21 -0
- unitbytes-1.0.0.dist-info/top_level.txt +1 -0
unitbytes/reddit.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
"""Reddit community, 5-tab search, post, comment tree, and user profile domain namespace (`ub.reddit`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from decimal import Decimal
|
|
6
|
+
import re
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Literal, Mapping
|
|
8
|
+
from urllib.parse import urlparse
|
|
9
|
+
|
|
10
|
+
from ._transports import unwrap_items_payload, unwrap_object_payload
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from .client import UnitBytes
|
|
14
|
+
|
|
15
|
+
ACTOR_REDDIT_ALL = "unitbytes/reddit-scraper"
|
|
16
|
+
ACTOR_REDDIT_SEARCH = "unitbytes/reddit-search-scraper"
|
|
17
|
+
ACTOR_REDDIT_SUBREDDITS = "unitbytes/reddit-subreddits-scraper"
|
|
18
|
+
ACTOR_REDDIT_COMMENTS = "unitbytes/reddit-comments-scraper"
|
|
19
|
+
ACTOR_REDDIT_USER = "unitbytes/reddit-user-scraper"
|
|
20
|
+
|
|
21
|
+
RedditSearchTab = Literal["posts", "communities", "people", "media", "comments"]
|
|
22
|
+
RedditSort = Literal["hot", "new", "top", "rising", "relevance", "comments"]
|
|
23
|
+
RedditTimeFilter = Literal["all", "year", "month", "week", "day", "hour"]
|
|
24
|
+
|
|
25
|
+
_VALID_TABS = {"posts", "communities", "people", "media", "comments"}
|
|
26
|
+
_VALID_SORTS = {"hot", "new", "top", "rising", "relevance", "comments"}
|
|
27
|
+
_VALID_TIMES = {"all", "year", "month", "week", "day", "hour"}
|
|
28
|
+
_POST_ID_RE = re.compile(r"^(?:t3_)?([a-z0-9]{5,10})$", re.IGNORECASE)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _validate_reddit_url(raw_url: str) -> str:
|
|
32
|
+
parsed = urlparse(raw_url)
|
|
33
|
+
if parsed.scheme not in {"http", "https"} or parsed.username or parsed.password:
|
|
34
|
+
raise ValueError(f"Invalid Reddit URL {raw_url!r}.")
|
|
35
|
+
host = (parsed.hostname or "").lower().rstrip(".")
|
|
36
|
+
if not (host in {"reddit.com", "old.reddit.com", "www.reddit.com", "redd.it"} or host.endswith(".reddit.com")):
|
|
37
|
+
raise ValueError(f"Expected a reddit.com URL, got host {host!r}.")
|
|
38
|
+
return raw_url
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _normalize_post_target(post_url_or_id: str) -> tuple[str | None, str]:
|
|
42
|
+
cleaned = str(post_url_or_id or "").strip()
|
|
43
|
+
if not cleaned:
|
|
44
|
+
raise ValueError("post_url_or_id cannot be empty.")
|
|
45
|
+
if cleaned.startswith(("http://", "https://")):
|
|
46
|
+
valid_u = _validate_reddit_url(cleaned)
|
|
47
|
+
return None, valid_u
|
|
48
|
+
m = _POST_ID_RE.fullmatch(cleaned)
|
|
49
|
+
if not m:
|
|
50
|
+
raise ValueError(f"Invalid Reddit post identifier {post_url_or_id!r}. Pass a post ID or reddit.com/r/.../comments/... URL.")
|
|
51
|
+
pid = m.group(1)
|
|
52
|
+
return pid, f"https://www.reddit.com/comments/{pid}/"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class RedditNamespace:
|
|
56
|
+
"""Reddit 5-tab search, subreddit feeds, posts, recursive comment trees, and user histories (`ub.reddit`)."""
|
|
57
|
+
|
|
58
|
+
def __init__(self, client: UnitBytes) -> None:
|
|
59
|
+
self._client = client
|
|
60
|
+
|
|
61
|
+
def search(
|
|
62
|
+
self,
|
|
63
|
+
query: str,
|
|
64
|
+
*,
|
|
65
|
+
tab: RedditSearchTab = "posts",
|
|
66
|
+
subreddit: str = "",
|
|
67
|
+
sort: RedditSort = "relevance",
|
|
68
|
+
time_filter: RedditTimeFilter = "all",
|
|
69
|
+
max_items: int = 20,
|
|
70
|
+
include_nsfw: bool = True,
|
|
71
|
+
scrape_comments: bool = False,
|
|
72
|
+
max_comments_per_post: int = 20,
|
|
73
|
+
after: str = "",
|
|
74
|
+
proxy_configuration: Mapping[str, Any] | None = None,
|
|
75
|
+
no_cache: bool = False,
|
|
76
|
+
max_total_charge_usd: float | Decimal | None = None,
|
|
77
|
+
) -> list[dict[str, Any]]:
|
|
78
|
+
"""Search Reddit across `posts`, `communities`, `people`, `media`, or `comments` tabs."""
|
|
79
|
+
cleaned_q = str(query or "").strip()
|
|
80
|
+
if not cleaned_q:
|
|
81
|
+
raise ValueError("query cannot be empty.")
|
|
82
|
+
if tab not in _VALID_TABS:
|
|
83
|
+
raise ValueError(f"Invalid tab {tab!r}. Expected {sorted(_VALID_TABS)}.")
|
|
84
|
+
if sort not in _VALID_SORTS:
|
|
85
|
+
raise ValueError(f"Invalid sort {sort!r}. Expected {sorted(_VALID_SORTS)}.")
|
|
86
|
+
if time_filter not in _VALID_TIMES:
|
|
87
|
+
raise ValueError(f"Invalid time_filter {time_filter!r}. Expected {sorted(_VALID_TIMES)}.")
|
|
88
|
+
|
|
89
|
+
clean_sub = str(subreddit or "").strip().removeprefix("r/").strip("/")
|
|
90
|
+
actor_input: dict[str, Any] = {
|
|
91
|
+
"searchQuery": cleaned_q,
|
|
92
|
+
"searchTab": tab,
|
|
93
|
+
"sort": sort,
|
|
94
|
+
"timeFilter": time_filter,
|
|
95
|
+
"maxItems": max(1, min(5000, int(max_items))),
|
|
96
|
+
"includeNSFW": bool(include_nsfw),
|
|
97
|
+
"scrapeComments": bool(scrape_comments),
|
|
98
|
+
"maxCommentsPerPost": max(1, min(500, int(max_comments_per_post))),
|
|
99
|
+
}
|
|
100
|
+
if clean_sub:
|
|
101
|
+
actor_input["subreddit"] = clean_sub
|
|
102
|
+
if proxy_configuration is not None:
|
|
103
|
+
actor_input["proxyConfiguration"] = dict(proxy_configuration)
|
|
104
|
+
|
|
105
|
+
rest_params: dict[str, Any] = {
|
|
106
|
+
"query": cleaned_q,
|
|
107
|
+
"tab": tab,
|
|
108
|
+
"subreddit": clean_sub or None,
|
|
109
|
+
"sort": sort,
|
|
110
|
+
"time_filter": time_filter,
|
|
111
|
+
"after": after or None,
|
|
112
|
+
"page_size": min(50, max(1, int(max_items))),
|
|
113
|
+
"include_nsfw": bool(include_nsfw),
|
|
114
|
+
"no_cache": no_cache or None,
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
raw = self._client._transport.execute_operation(
|
|
118
|
+
service="reddit",
|
|
119
|
+
operation="search",
|
|
120
|
+
actor_slug=ACTOR_REDDIT_SEARCH,
|
|
121
|
+
actor_input=actor_input,
|
|
122
|
+
http_method="GET",
|
|
123
|
+
params=rest_params,
|
|
124
|
+
max_total_charge_usd=max_total_charge_usd,
|
|
125
|
+
)
|
|
126
|
+
return [r for r in unwrap_items_payload(raw) if not r.get("error")]
|
|
127
|
+
|
|
128
|
+
def subreddit(
|
|
129
|
+
self,
|
|
130
|
+
subreddit_or_url: str,
|
|
131
|
+
*,
|
|
132
|
+
sort: Literal["hot", "new", "top", "rising"] = "hot",
|
|
133
|
+
time_filter: RedditTimeFilter = "all",
|
|
134
|
+
max_items: int = 25,
|
|
135
|
+
include_nsfw: bool = True,
|
|
136
|
+
skip_pinned: bool = False,
|
|
137
|
+
scrape_comments: bool = False,
|
|
138
|
+
max_comments_per_post: int = 20,
|
|
139
|
+
after: str = "",
|
|
140
|
+
proxy_configuration: Mapping[str, Any] | None = None,
|
|
141
|
+
no_cache: bool = False,
|
|
142
|
+
max_total_charge_usd: float | Decimal | None = None,
|
|
143
|
+
) -> list[dict[str, Any]]:
|
|
144
|
+
"""Extract community feed posts from a subreddit name (`'technology'`) or Reddit community URL."""
|
|
145
|
+
cleaned = str(subreddit_or_url or "").strip()
|
|
146
|
+
if not cleaned:
|
|
147
|
+
raise ValueError("subreddit_or_url cannot be empty.")
|
|
148
|
+
|
|
149
|
+
is_url = cleaned.startswith(("http://", "https://"))
|
|
150
|
+
if is_url:
|
|
151
|
+
_validate_reddit_url(cleaned)
|
|
152
|
+
sub_name = ""
|
|
153
|
+
else:
|
|
154
|
+
sub_name = cleaned.removeprefix("r/").removeprefix("/r/").strip("/")
|
|
155
|
+
|
|
156
|
+
actor_input: dict[str, Any] = {
|
|
157
|
+
"sort": sort,
|
|
158
|
+
"timeFilter": time_filter,
|
|
159
|
+
"maxItems": max(1, min(5000, int(max_items))),
|
|
160
|
+
"includeNSFW": bool(include_nsfw),
|
|
161
|
+
"skipPinned": bool(skip_pinned),
|
|
162
|
+
"scrapeComments": bool(scrape_comments),
|
|
163
|
+
"maxCommentsPerPost": max(1, min(500, int(max_comments_per_post))),
|
|
164
|
+
}
|
|
165
|
+
if is_url:
|
|
166
|
+
actor_input["startUrls"] = [{"url": cleaned}]
|
|
167
|
+
else:
|
|
168
|
+
actor_input["subreddit"] = sub_name
|
|
169
|
+
if proxy_configuration is not None:
|
|
170
|
+
actor_input["proxyConfiguration"] = dict(proxy_configuration)
|
|
171
|
+
|
|
172
|
+
rest_params: dict[str, Any] = {
|
|
173
|
+
"subreddit": sub_name or None,
|
|
174
|
+
"url": cleaned if is_url else None,
|
|
175
|
+
"sort": sort,
|
|
176
|
+
"time_filter": time_filter,
|
|
177
|
+
"after": after or None,
|
|
178
|
+
"page_size": min(50, max(1, int(max_items))),
|
|
179
|
+
"include_nsfw": bool(include_nsfw),
|
|
180
|
+
"no_cache": no_cache or None,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
raw = self._client._transport.execute_operation(
|
|
184
|
+
service="reddit",
|
|
185
|
+
operation="subreddit",
|
|
186
|
+
actor_slug=ACTOR_REDDIT_SUBREDDITS,
|
|
187
|
+
actor_input=actor_input,
|
|
188
|
+
http_method="GET",
|
|
189
|
+
params=rest_params,
|
|
190
|
+
max_total_charge_usd=max_total_charge_usd,
|
|
191
|
+
)
|
|
192
|
+
return [r for r in unwrap_items_payload(raw) if not r.get("error")]
|
|
193
|
+
|
|
194
|
+
def post(
|
|
195
|
+
self,
|
|
196
|
+
post_url_or_id: str,
|
|
197
|
+
*,
|
|
198
|
+
max_comments: int = 50,
|
|
199
|
+
proxy_configuration: Mapping[str, Any] | None = None,
|
|
200
|
+
no_cache: bool = False,
|
|
201
|
+
max_total_charge_usd: float | Decimal | None = None,
|
|
202
|
+
) -> dict[str, Any]:
|
|
203
|
+
"""Fetch a single Reddit post and its inline top comments by post ID or thread URL."""
|
|
204
|
+
post_id, post_url = _normalize_post_target(post_url_or_id)
|
|
205
|
+
actor_input: dict[str, Any] = {
|
|
206
|
+
"startUrls": [{"url": post_url}],
|
|
207
|
+
"maxItems": 1,
|
|
208
|
+
"scrapeComments": True,
|
|
209
|
+
"maxCommentsPerPost": max(1, min(500, int(max_comments))),
|
|
210
|
+
}
|
|
211
|
+
if proxy_configuration is not None:
|
|
212
|
+
actor_input["proxyConfiguration"] = dict(proxy_configuration)
|
|
213
|
+
|
|
214
|
+
rest_params: dict[str, Any] = {
|
|
215
|
+
"post_id": post_id,
|
|
216
|
+
"url": post_url if not post_id else None,
|
|
217
|
+
"max_comments": max(1, min(500, int(max_comments))),
|
|
218
|
+
"no_cache": no_cache or None,
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
raw = self._client._transport.execute_operation(
|
|
222
|
+
service="reddit",
|
|
223
|
+
operation="post",
|
|
224
|
+
actor_slug=ACTOR_REDDIT_ALL,
|
|
225
|
+
actor_input=actor_input,
|
|
226
|
+
http_method="GET",
|
|
227
|
+
params=rest_params,
|
|
228
|
+
max_total_charge_usd=max_total_charge_usd,
|
|
229
|
+
)
|
|
230
|
+
return unwrap_object_payload(raw)
|
|
231
|
+
|
|
232
|
+
def comments(
|
|
233
|
+
self,
|
|
234
|
+
post_url_or_id: str,
|
|
235
|
+
*,
|
|
236
|
+
max_comments: int = 100,
|
|
237
|
+
sort: Literal["top", "new", "hot", "comments"] = "top",
|
|
238
|
+
proxy_configuration: Mapping[str, Any] | None = None,
|
|
239
|
+
no_cache: bool = False,
|
|
240
|
+
max_total_charge_usd: float | Decimal | None = None,
|
|
241
|
+
) -> list[dict[str, Any]]:
|
|
242
|
+
"""Extract nested discussion comments from a Reddit thread URL or post ID."""
|
|
243
|
+
post_id, post_url = _normalize_post_target(post_url_or_id)
|
|
244
|
+
actor_input: dict[str, Any] = {
|
|
245
|
+
"startUrls": [{"url": post_url}],
|
|
246
|
+
"scrapeComments": True,
|
|
247
|
+
"maxCommentsPerPost": max(1, min(500, int(max_comments))),
|
|
248
|
+
"sort": sort,
|
|
249
|
+
}
|
|
250
|
+
if proxy_configuration is not None:
|
|
251
|
+
actor_input["proxyConfiguration"] = dict(proxy_configuration)
|
|
252
|
+
|
|
253
|
+
rest_params: dict[str, Any] = {
|
|
254
|
+
"post_id": post_id,
|
|
255
|
+
"url": post_url if not post_id else None,
|
|
256
|
+
"max_comments": max(1, min(500, int(max_comments))),
|
|
257
|
+
"sort": sort,
|
|
258
|
+
"no_cache": no_cache or None,
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
raw = self._client._transport.execute_operation(
|
|
262
|
+
service="reddit",
|
|
263
|
+
operation="comments",
|
|
264
|
+
actor_slug=ACTOR_REDDIT_COMMENTS,
|
|
265
|
+
actor_input=actor_input,
|
|
266
|
+
http_method="GET",
|
|
267
|
+
params=rest_params,
|
|
268
|
+
max_total_charge_usd=max_total_charge_usd,
|
|
269
|
+
)
|
|
270
|
+
return [r for r in unwrap_items_payload(raw) if not r.get("error")]
|
|
271
|
+
|
|
272
|
+
def user(
|
|
273
|
+
self,
|
|
274
|
+
username_or_url: str,
|
|
275
|
+
*,
|
|
276
|
+
tab: Literal["posts", "comments"] = "posts",
|
|
277
|
+
sort: Literal["new", "hot", "top"] = "new",
|
|
278
|
+
time_filter: RedditTimeFilter = "all",
|
|
279
|
+
max_items: int = 25,
|
|
280
|
+
include_nsfw: bool = True,
|
|
281
|
+
scrape_comments: bool = False,
|
|
282
|
+
max_comments_per_post: int = 20,
|
|
283
|
+
after: str = "",
|
|
284
|
+
proxy_configuration: Mapping[str, Any] | None = None,
|
|
285
|
+
no_cache: bool = False,
|
|
286
|
+
max_total_charge_usd: float | Decimal | None = None,
|
|
287
|
+
) -> list[dict[str, Any]]:
|
|
288
|
+
"""Extract submitted posts or authored comment history for a Reddit user."""
|
|
289
|
+
cleaned = str(username_or_url or "").strip()
|
|
290
|
+
if not cleaned:
|
|
291
|
+
raise ValueError("username_or_url cannot be empty.")
|
|
292
|
+
|
|
293
|
+
is_url = cleaned.startswith(("http://", "https://"))
|
|
294
|
+
if is_url:
|
|
295
|
+
_validate_reddit_url(cleaned)
|
|
296
|
+
uname = ""
|
|
297
|
+
else:
|
|
298
|
+
uname = cleaned.removeprefix("u/").removeprefix("/u/").removeprefix("user/").strip("/")
|
|
299
|
+
|
|
300
|
+
actor_input: dict[str, Any] = {
|
|
301
|
+
"searchTab": "comments" if tab == "comments" else "posts",
|
|
302
|
+
"sort": sort,
|
|
303
|
+
"timeFilter": time_filter,
|
|
304
|
+
"maxItems": max(1, min(5000, int(max_items))),
|
|
305
|
+
"includeNSFW": bool(include_nsfw),
|
|
306
|
+
"scrapeComments": bool(scrape_comments),
|
|
307
|
+
"maxCommentsPerPost": max(1, min(500, int(max_comments_per_post))),
|
|
308
|
+
}
|
|
309
|
+
if is_url:
|
|
310
|
+
actor_input["startUrls"] = [{"url": cleaned}]
|
|
311
|
+
else:
|
|
312
|
+
actor_input["username"] = uname
|
|
313
|
+
if proxy_configuration is not None:
|
|
314
|
+
actor_input["proxyConfiguration"] = dict(proxy_configuration)
|
|
315
|
+
|
|
316
|
+
rest_params: dict[str, Any] = {
|
|
317
|
+
"username": uname or None,
|
|
318
|
+
"url": cleaned if is_url else None,
|
|
319
|
+
"tab": tab,
|
|
320
|
+
"sort": sort,
|
|
321
|
+
"time_filter": time_filter,
|
|
322
|
+
"after": after or None,
|
|
323
|
+
"page_size": min(50, max(1, int(max_items))),
|
|
324
|
+
"include_nsfw": bool(include_nsfw),
|
|
325
|
+
"include_comments": bool(scrape_comments),
|
|
326
|
+
"max_comments": max(1, min(500, int(max_comments_per_post))),
|
|
327
|
+
"no_cache": no_cache or None,
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
raw = self._client._transport.execute_operation(
|
|
331
|
+
service="reddit",
|
|
332
|
+
operation="user",
|
|
333
|
+
actor_slug=ACTOR_REDDIT_USER,
|
|
334
|
+
actor_input=actor_input,
|
|
335
|
+
http_method="GET",
|
|
336
|
+
params=rest_params,
|
|
337
|
+
max_total_charge_usd=max_total_charge_usd,
|
|
338
|
+
)
|
|
339
|
+
return [r for r in unwrap_items_payload(raw) if not r.get("error")]
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
__all__ = ["RedditNamespace"]
|
unitbytes/rednote.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""RedNote / Xiaohongshu (`小红书`) social commerce domain namespace (`ub.rednote`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from decimal import Decimal
|
|
6
|
+
import re
|
|
7
|
+
import urllib.parse
|
|
8
|
+
from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
|
|
9
|
+
|
|
10
|
+
from ._transports import unwrap_items_payload, unwrap_object_payload
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from .client import UnitBytes
|
|
14
|
+
|
|
15
|
+
ACTOR_REDNOTE_SEARCH = "unitbytes/rednote-xiaohongshu-search-scraper"
|
|
16
|
+
ACTOR_REDNOTE_TREND = "unitbytes/xiaohongshu-rednote-trend-scraper"
|
|
17
|
+
ACTOR_REDNOTE_COMMENTS = "unitbytes/xiaohongshu-rednote-comments-scraper"
|
|
18
|
+
ACTOR_REDNOTE_PROFILE = "unitbytes/xiaohongshu-rednote-profile-scraper"
|
|
19
|
+
|
|
20
|
+
SortOrder = Literal["popularity_descending", "general", "time_descending"]
|
|
21
|
+
NoteType = Literal["all", "video_only", "image_only"]
|
|
22
|
+
|
|
23
|
+
_HEX_24_RE = re.compile(r"^[0-9a-fA-F]{24}$")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _validate_xhs_url(raw_url: str, label: str) -> str:
|
|
27
|
+
parsed = urllib.parse.urlsplit(raw_url)
|
|
28
|
+
if parsed.scheme not in ("http", "https") or parsed.username or parsed.password or "@" in (parsed.netloc or ""):
|
|
29
|
+
raise ValueError(f"Invalid Xiaohongshu {label} URL {raw_url!r}.")
|
|
30
|
+
host = (parsed.hostname or "").lower().rstrip(".")
|
|
31
|
+
allowed = (
|
|
32
|
+
host in ("xiaohongshu.com", "rednote.com", "xhslink.com")
|
|
33
|
+
or host.endswith((".xiaohongshu.com", ".rednote.com", ".xhslink.com"))
|
|
34
|
+
)
|
|
35
|
+
if not allowed:
|
|
36
|
+
raise ValueError(
|
|
37
|
+
f"Disallowed host {host!r} in Xiaohongshu {label} URL {raw_url!r}. "
|
|
38
|
+
"Expected xiaohongshu.com, rednote.com, or xhslink.com."
|
|
39
|
+
)
|
|
40
|
+
return raw_url
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def normalize_note_url(url_or_id: str) -> str:
|
|
44
|
+
"""Normalize a bare 24-hex Note ID, share link, or explore link into a clean URL."""
|
|
45
|
+
cleaned = str(url_or_id).strip()
|
|
46
|
+
if not cleaned:
|
|
47
|
+
raise ValueError("url_or_id must be a non-empty Xiaohongshu Note URL or 24-hex Note ID.")
|
|
48
|
+
if _HEX_24_RE.match(cleaned):
|
|
49
|
+
return f"https://www.xiaohongshu.com/explore/{cleaned.lower()}"
|
|
50
|
+
if cleaned.startswith(("http://", "https://")):
|
|
51
|
+
return _validate_xhs_url(cleaned, "note")
|
|
52
|
+
if cleaned.startswith("/explore/"):
|
|
53
|
+
return f"https://www.xiaohongshu.com{cleaned}"
|
|
54
|
+
raise ValueError(
|
|
55
|
+
f"Invalid Xiaohongshu note identifier {url_or_id!r}. Pass a full URL or 24-character hex Note ID."
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def normalize_profile_url(user_url_or_id: str) -> str:
|
|
60
|
+
"""Normalize a bare 24-hex User ID or creator profile URL into a clean URL."""
|
|
61
|
+
cleaned = str(user_url_or_id).strip()
|
|
62
|
+
if not cleaned:
|
|
63
|
+
raise ValueError("user_url_or_id must be a non-empty Creator URL or 24-hex User ID.")
|
|
64
|
+
if _HEX_24_RE.match(cleaned):
|
|
65
|
+
return f"https://www.xiaohongshu.com/user/profile/{cleaned.lower()}"
|
|
66
|
+
if cleaned.startswith(("http://", "https://")):
|
|
67
|
+
return _validate_xhs_url(cleaned, "creator")
|
|
68
|
+
if cleaned.startswith("/user/profile/"):
|
|
69
|
+
return f"https://www.xiaohongshu.com{cleaned}"
|
|
70
|
+
raise ValueError(
|
|
71
|
+
f"Invalid Xiaohongshu creator identifier {user_url_or_id!r}. Pass a profile URL or 24-character hex User ID."
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _normalize_keywords(keywords: str | Sequence[str]) -> list[str]:
|
|
76
|
+
items = [keywords.strip()] if isinstance(keywords, str) else [str(k).strip() for k in keywords]
|
|
77
|
+
cleaned = [k for k in items if k]
|
|
78
|
+
if not cleaned:
|
|
79
|
+
raise ValueError("keywords must contain at least one non-empty search query.")
|
|
80
|
+
return cleaned
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class RednoteNamespace:
|
|
84
|
+
"""RedNote / Xiaohongshu (`小红书`) search, creator profiles, comments, and category trends (`ub.rednote`)."""
|
|
85
|
+
|
|
86
|
+
def __init__(self, client: UnitBytes) -> None:
|
|
87
|
+
self._client = client
|
|
88
|
+
|
|
89
|
+
def search(
|
|
90
|
+
self,
|
|
91
|
+
keywords: str | Sequence[str],
|
|
92
|
+
*,
|
|
93
|
+
sort: SortOrder = "popularity_descending",
|
|
94
|
+
note_type: NoteType = "all",
|
|
95
|
+
max_items: int = 30,
|
|
96
|
+
page: int = 1,
|
|
97
|
+
enrich_details: bool = True,
|
|
98
|
+
include_author_profile: bool = False,
|
|
99
|
+
proxy_configuration: Mapping[str, Any] | None = None,
|
|
100
|
+
no_cache: bool = False,
|
|
101
|
+
max_total_charge_usd: float | Decimal | None = None,
|
|
102
|
+
) -> list[dict[str, Any]]:
|
|
103
|
+
"""Search Xiaohongshu / RedNote posts by keyword(s) without cookies or login."""
|
|
104
|
+
kw_list = _normalize_keywords(keywords)
|
|
105
|
+
target_actor = ACTOR_REDNOTE_TREND if include_author_profile else ACTOR_REDNOTE_SEARCH
|
|
106
|
+
actor_input: dict[str, Any] = {
|
|
107
|
+
"keywords": kw_list,
|
|
108
|
+
"sort": sort,
|
|
109
|
+
"noteType": note_type,
|
|
110
|
+
"maxItems": max(1, int(max_items)),
|
|
111
|
+
"enrichDetails": bool(enrich_details),
|
|
112
|
+
}
|
|
113
|
+
if target_actor != ACTOR_REDNOTE_SEARCH:
|
|
114
|
+
actor_input["mode"] = "search"
|
|
115
|
+
actor_input["includeAuthorProfile"] = bool(include_author_profile)
|
|
116
|
+
if proxy_configuration is not None:
|
|
117
|
+
actor_input["proxyConfiguration"] = dict(proxy_configuration)
|
|
118
|
+
|
|
119
|
+
rest_params: dict[str, Any] = {
|
|
120
|
+
"keyword": kw_list[0],
|
|
121
|
+
"sort_by": sort,
|
|
122
|
+
"page_size": min(40, max(1, int(max_items))),
|
|
123
|
+
"page": int(page),
|
|
124
|
+
"no_cache": no_cache or None,
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
raw = self._client._transport.execute_operation(
|
|
128
|
+
service="rednote",
|
|
129
|
+
operation="search",
|
|
130
|
+
actor_slug=target_actor,
|
|
131
|
+
actor_input=actor_input,
|
|
132
|
+
http_method="GET",
|
|
133
|
+
params=rest_params,
|
|
134
|
+
max_total_charge_usd=max_total_charge_usd,
|
|
135
|
+
)
|
|
136
|
+
return [r for r in unwrap_items_payload(raw) if not r.get("error")]
|
|
137
|
+
|
|
138
|
+
def profile(
|
|
139
|
+
self,
|
|
140
|
+
user_url_or_id: str,
|
|
141
|
+
*,
|
|
142
|
+
scrape_portfolio: bool = True,
|
|
143
|
+
max_notes_per_creator: int = 15,
|
|
144
|
+
enrich_note_details: bool = True,
|
|
145
|
+
proxy_configuration: Mapping[str, Any] | None = None,
|
|
146
|
+
no_cache: bool = False,
|
|
147
|
+
max_total_charge_usd: float | Decimal | None = None,
|
|
148
|
+
) -> dict[str, Any] | None:
|
|
149
|
+
"""Fetch a creator's full public RedNote profile (and optional latest portfolio notes)."""
|
|
150
|
+
raw_target = str(user_url_or_id).strip()
|
|
151
|
+
target_url = normalize_profile_url(raw_target)
|
|
152
|
+
is_hex = bool(_HEX_24_RE.match(raw_target))
|
|
153
|
+
|
|
154
|
+
actor_input: dict[str, Any] = {
|
|
155
|
+
"mode": "creators",
|
|
156
|
+
"creatorUrls": [{"url": target_url}],
|
|
157
|
+
"maxCreators": 1,
|
|
158
|
+
"scrapePortfolio": bool(scrape_portfolio),
|
|
159
|
+
"maxNotesPerCreator": int(max_notes_per_creator),
|
|
160
|
+
"enrichNoteDetails": bool(enrich_note_details),
|
|
161
|
+
}
|
|
162
|
+
if proxy_configuration is not None:
|
|
163
|
+
actor_input["proxyConfiguration"] = dict(proxy_configuration)
|
|
164
|
+
|
|
165
|
+
rest_params: dict[str, Any] = {
|
|
166
|
+
"user_id": raw_target.lower() if is_hex else None,
|
|
167
|
+
"url": target_url if not is_hex else None,
|
|
168
|
+
"include_notes": bool(scrape_portfolio),
|
|
169
|
+
"no_cache": no_cache or None,
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
raw = self._client._transport.execute_operation(
|
|
173
|
+
service="rednote",
|
|
174
|
+
operation="user",
|
|
175
|
+
actor_slug=ACTOR_REDNOTE_PROFILE,
|
|
176
|
+
actor_input=actor_input,
|
|
177
|
+
http_method="GET",
|
|
178
|
+
params=rest_params,
|
|
179
|
+
max_total_charge_usd=max_total_charge_usd,
|
|
180
|
+
)
|
|
181
|
+
if isinstance(raw, list):
|
|
182
|
+
if not raw:
|
|
183
|
+
return None
|
|
184
|
+
profiles = [i for i in raw if isinstance(i, Mapping) and i.get("itemType") == "creator_profile"]
|
|
185
|
+
portfolio_notes = [dict(i) for i in raw if isinstance(i, Mapping) and i.get("itemType") == "portfolio_note"]
|
|
186
|
+
primary = dict(profiles[0] if profiles else raw[0])
|
|
187
|
+
if scrape_portfolio or portfolio_notes:
|
|
188
|
+
primary.setdefault("portfolioNotes", portfolio_notes)
|
|
189
|
+
return primary
|
|
190
|
+
obj = unwrap_object_payload(raw)
|
|
191
|
+
return obj or None
|
|
192
|
+
|
|
193
|
+
def comments(
|
|
194
|
+
self,
|
|
195
|
+
url_or_id: str | Sequence[str],
|
|
196
|
+
*,
|
|
197
|
+
max_comments: int = 100,
|
|
198
|
+
include_replies: bool = True,
|
|
199
|
+
max_replies_per_comment: int = 3,
|
|
200
|
+
cursor: str = "",
|
|
201
|
+
proxy_configuration: Mapping[str, Any] | None = None,
|
|
202
|
+
no_cache: bool = False,
|
|
203
|
+
max_total_charge_usd: float | Decimal | None = None,
|
|
204
|
+
) -> list[dict[str, Any]]:
|
|
205
|
+
"""Extract multi-page comments and inline replies (`楼中楼`) from bare Note URLs or 24-hex IDs."""
|
|
206
|
+
targets = [url_or_id] if isinstance(url_or_id, str) else list(url_or_id)
|
|
207
|
+
if not targets:
|
|
208
|
+
raise ValueError("url_or_id must contain at least one note URL or 24-hex ID.")
|
|
209
|
+
start_urls = [{"url": normalize_note_url(t)} for t in targets]
|
|
210
|
+
|
|
211
|
+
actor_input: dict[str, Any] = {
|
|
212
|
+
"mode": "comments",
|
|
213
|
+
"startUrls": start_urls,
|
|
214
|
+
"maxCommentsPerNote": int(max_comments),
|
|
215
|
+
"includeSubComments": bool(include_replies),
|
|
216
|
+
"maxSubCommentsPerComment": max(1, min(3, int(max_replies_per_comment))),
|
|
217
|
+
}
|
|
218
|
+
if proxy_configuration is not None:
|
|
219
|
+
actor_input["proxyConfiguration"] = dict(proxy_configuration)
|
|
220
|
+
|
|
221
|
+
first = str(targets[0]).strip()
|
|
222
|
+
is_hex = bool(_HEX_24_RE.match(first))
|
|
223
|
+
rest_params: dict[str, Any] = {
|
|
224
|
+
"note_id": first.lower() if is_hex else None,
|
|
225
|
+
"url": start_urls[0]["url"] if not is_hex else None,
|
|
226
|
+
"cursor": cursor or None,
|
|
227
|
+
"include_replies": bool(include_replies),
|
|
228
|
+
"page_size": min(50, max(1, int(max_comments))),
|
|
229
|
+
"no_cache": no_cache or None,
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
raw = self._client._transport.execute_operation(
|
|
233
|
+
service="rednote",
|
|
234
|
+
operation="comments",
|
|
235
|
+
actor_slug=ACTOR_REDNOTE_COMMENTS,
|
|
236
|
+
actor_input=actor_input,
|
|
237
|
+
http_method="GET",
|
|
238
|
+
params=rest_params,
|
|
239
|
+
max_total_charge_usd=max_total_charge_usd,
|
|
240
|
+
)
|
|
241
|
+
return [r for r in unwrap_items_payload(raw) if not r.get("error")]
|
|
242
|
+
|
|
243
|
+
def trends(
|
|
244
|
+
self,
|
|
245
|
+
*,
|
|
246
|
+
channels: Sequence[str] = ("homefeed_recommend",),
|
|
247
|
+
note_type: NoteType = "all",
|
|
248
|
+
max_items: int = 30,
|
|
249
|
+
enrich_details: bool = True,
|
|
250
|
+
include_author_profile: bool = False,
|
|
251
|
+
proxy_configuration: Mapping[str, Any] | None = None,
|
|
252
|
+
no_cache: bool = False,
|
|
253
|
+
max_total_charge_usd: float | Decimal | None = None,
|
|
254
|
+
) -> list[dict[str, Any]]:
|
|
255
|
+
"""Fetch viral posts across Xiaohongshu's official category explore channels."""
|
|
256
|
+
chan_list = [str(c).strip() for c in channels if str(c).strip()] or ["homefeed_recommend"]
|
|
257
|
+
actor_input: dict[str, Any] = {
|
|
258
|
+
"mode": "trending",
|
|
259
|
+
"channels": chan_list,
|
|
260
|
+
"noteType": note_type,
|
|
261
|
+
"maxItems": max(1, int(max_items)),
|
|
262
|
+
"enrichDetails": bool(enrich_details),
|
|
263
|
+
"includeAuthorProfile": bool(include_author_profile),
|
|
264
|
+
}
|
|
265
|
+
if proxy_configuration is not None:
|
|
266
|
+
actor_input["proxyConfiguration"] = dict(proxy_configuration)
|
|
267
|
+
|
|
268
|
+
rest_params: dict[str, Any] = {
|
|
269
|
+
"category": chan_list[0],
|
|
270
|
+
"page_size": min(40, max(1, int(max_items))),
|
|
271
|
+
"no_cache": no_cache or None,
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
raw = self._client._transport.execute_operation(
|
|
275
|
+
service="rednote",
|
|
276
|
+
operation="trending",
|
|
277
|
+
actor_slug=ACTOR_REDNOTE_TREND,
|
|
278
|
+
actor_input=actor_input,
|
|
279
|
+
http_method="GET",
|
|
280
|
+
params=rest_params,
|
|
281
|
+
max_total_charge_usd=max_total_charge_usd,
|
|
282
|
+
)
|
|
283
|
+
return [r for r in unwrap_items_payload(raw) if not r.get("error")]
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
__all__ = ["RednoteNamespace", "normalize_note_url", "normalize_profile_url"]
|
unitbytes/request.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Compatibility shim so `from unitbytes.request import TrendReq` mirrors `from pytrends.request import TrendReq`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .trends import ResponseError, TooManyRequestsError, TrendReq
|
|
6
|
+
|
|
7
|
+
__all__ = ["TrendReq", "ResponseError", "TooManyRequestsError"]
|