vinted_scraper
Vinted Scraper - A Python package for scraping Vinted marketplace.
This package provides both synchronous and asynchronous clients for interacting with the Vinted API. Choose between typed model responses (Scraper) or raw JSON responses (Wrapper).
Classes: VintedScraper: Synchronous client with typed VintedItem responses. VintedWrapper: Synchronous client with raw JSON responses. AsyncVintedScraper: Asynchronous client with typed VintedItem responses. AsyncVintedWrapper: Asynchronous client with raw JSON responses.
Examples:
See https://github.com/Giglium/vinted_scraper/tree/main/examples
1"""Vinted Scraper - A Python package for scraping Vinted marketplace. 2 3This package provides both synchronous and asynchronous clients for interacting 4with the Vinted API. Choose between typed model responses (Scraper) or raw JSON 5responses (Wrapper). 6 7Classes: 8 VintedScraper: Synchronous client with typed VintedItem responses. 9 VintedWrapper: Synchronous client with raw JSON responses. 10 AsyncVintedScraper: Asynchronous client with typed VintedItem responses. 11 AsyncVintedWrapper: Asynchronous client with raw JSON responses. 12 13 Examples: 14 See https://github.com/Giglium/vinted_scraper/tree/main/examples 15""" 16 17from ._async_scraper import AsyncVintedScraper 18from ._async_wrapper import AsyncVintedWrapper 19from ._scraper import VintedScraper 20from ._wrapper import VintedWrapper 21from .models import OgField, VintedSession 22 23__all__ = [ 24 "AsyncVintedWrapper", 25 "VintedWrapper", 26 "AsyncVintedScraper", 27 "VintedScraper", 28 "OgField", 29 "VintedSession", 30]
40@dataclass 41class AsyncVintedWrapper(BaseVintedWrapper): 42 """Asynchronous Vinted API wrapper returning raw JSON responses. 43 44 Handles cookie management, retries, and async HTTP requests automatically. 45 Returns raw JSON dictionaries instead of typed objects. 46 47 Attributes: 48 baseurl: Vinted domain URL (e.g., "https://www.vinted.com"). 49 session: API identity (VintedSession). Auto-fetched if None or empty. 50 user_agent: Custom user agent string. Auto-generated if None. 51 config: httpx client configuration dict. 52 cookie_names: List of cookie names to extract. Defaults to ["access_token_web"]. 53 locale: Optional ``Locale`` override (e.g. "en-US"). Read from the 54 landing page when None, falling back to a guess from ``baseurl``. 55 56 Example: 57 See https://github.com/Giglium/vinted_scraper/blob/main/examples/async_wrapper.py 58 """ 59 60 _client: httpx.AsyncClient = field(init=False, repr=False) 61 _api_client: httpx.AsyncClient = field(init=False, repr=False) 62 63 @classmethod 64 async def create( 65 cls, 66 baseurl: str, 67 user_agent: Optional[str] = None, 68 config: Optional[Dict] = None, 69 cookie_names: Optional[List[str]] = None, 70 session: Optional[VintedSession] = None, 71 locale: Optional[str] = None, 72 ): 73 """Factory method to create an AsyncVintedWrapper instance. 74 75 Use this instead of direct instantiation to automatically fetch the 76 session identity. Pass 77 ``session`` to reuse a prefetched one and skip the network fetch. 78 79 Args: 80 baseurl: Vinted domain URL (e.g., "https://www.vinted.com"). 81 user_agent: Custom user agent string. Auto-generated if None. 82 config: httpx client configuration dict. 83 cookie_names: List of cookie names to extract. Defaults to ["access_token_web"]. 84 session: A prefetched ``VintedSession``. Auto-fetched if None/empty. 85 locale: Optional ``Locale`` override. When None, the locale is read 86 from the landing page, falling back to a guess from ``baseurl``. 87 88 Returns: 89 Initialized AsyncVintedWrapper instance with a resolved session. 90 """ 91 _log.debug("Creating the async wrapper using the factory method") 92 self = cls( 93 baseurl, 94 session=session, 95 user_agent=user_agent, 96 config=config, 97 cookie_names=cookie_names, 98 locale=locale, 99 ) 100 if self._needs_session(): 101 await self.refresh_session() 102 return self 103 104 def __post_init__(self) -> None: 105 """Initialize AsyncVintedWrapper after dataclass initialization. 106 107 Validates the base URL, sets up user agent, and initializes the two 108 httpx async clients (site host and ``api.`` host). 109 110 Raises: 111 RuntimeError: If the base URL is invalid. 112 113 Note: 114 Use the create() factory method instead of direct instantiation to 115 automatically fetch the session cookie. 116 """ 117 site_config, api_config = self._validate_and_init() 118 self._client = httpx.AsyncClient(**site_config) 119 self._api_client = httpx.AsyncClient(**api_config) 120 121 async def refresh_session(self, retries: int = DEFAULT_RETRIES) -> VintedSession: 122 """Manually refresh the session cookie and API tokens. 123 124 Args: 125 retries: Number of retry attempts (default: 3). 126 127 Returns: 128 The ``VintedSession`` returned by :meth:`fetch_session`. 129 130 Raises: 131 RuntimeError: If cookies cannot be fetched after all retries. 132 """ 133 log_refresh_cookie(_log) 134 session = await AsyncVintedWrapper.fetch_session( 135 self._client, 136 self._get_cookie_headers(), 137 self.cookie_names, 138 retries, 139 ) 140 self.session = session 141 return session 142 143 @staticmethod 144 async def fetch_session( 145 client: httpx.AsyncClient, 146 headers: Dict, 147 cookie_names: List[str], 148 retries: int = DEFAULT_RETRIES, 149 ) -> VintedSession: 150 """Fetch the full session identity from Vinted's landing page (async). 151 152 Args: 153 client: httpx.AsyncClient instance. 154 headers: HTTP headers dictionary. 155 cookie_names: List of cookie names to extract. 156 retries: Number of retry attempts (default: 3). 157 158 Returns: 159 A ``VintedSession`` with the cookies, CSRF token and anonymous id. 160 161 Raises: 162 RuntimeError: If cookies cannot be fetched after all retries. 163 """ 164 response = None 165 166 for i in range(retries): 167 log_interaction(_log, i, retries) 168 html, response = await AsyncVintedWrapper._stream_until( 169 client, "/", headers, CSRF_MARKER 170 ) 171 172 if response.status_code == HTTP_OK: 173 session = build_session(response, html, cookie_names) 174 if session.is_usable(): 175 return session 176 177 sleep_time = handle_session_failure(response, i, retries) 178 if i < retries - 1: 179 await asyncio.sleep(sleep_time) 180 181 raise_session_error(client.base_url, response) 182 183 @staticmethod 184 async def _stream_until( 185 client: httpx.AsyncClient, url: str, headers: Dict, stop_marker: str 186 ) -> Tuple[str, httpx.Response]: 187 """Stream ``url``, reading only up to ``stop_marker``. 188 189 Shared by :meth:`item` (stops at ``</head>``) and the session fetch 190 (stops at the CSRF marker) so that neither downloads the full page body. 191 The chunk-boundary bookkeeping lives in :class:`ChunkAccumulator`. 192 193 Args: 194 client: httpx.AsyncClient instance. 195 url: The URL or endpoint path to request. 196 headers: Request headers for the GET. 197 stop_marker: The text marker that ends the read. 198 199 Returns: 200 Tuple of ``(html, response)``. ``html`` is empty for non-200 201 responses. 202 """ 203 acc = ChunkAccumulator(stop_marker) 204 async with client.stream("GET", url, headers=headers) as response: 205 if response.status_code == HTTP_OK: 206 async for chunk in response.aiter_text(chunk_size=STREAM_CHUNK_SIZE): 207 if acc.add(chunk): 208 break 209 else: 210 await response.aread() 211 return acc.text, response 212 213 async def search(self, params: Optional[Dict] = None) -> Dict[str, Any]: 214 """Search for items on Vinted asynchronously. 215 216 Args: 217 params: Query parameters. Common parameters: 218 - search_text: Search query 219 - page: Page number 220 - per_page: Items per page 221 - price_from: Minimum price 222 - price_to: Maximum price 223 - order: Sort order 224 - attribute_ids[catalog]: Category IDs (comma-separated; 225 - attribute_ids[status]: Condition IDs (comma-separated; 226 - attribute_ids[brand]: Brand IDs (comma-separated; 227 - attribute_ids[size]: Size IDs (comma-separated; 228 229 Returns: 230 Dictionary containing JSON response with search results. 231 """ 232 log_search(_log, params) 233 return await self.curl( 234 self._search_endpoint(), params=params, api_endpoint=True 235 ) 236 237 async def get_user(self, user_id: Union[int, str]) -> Dict[str, Any]: 238 """Read a user's profile. 239 240 Args: 241 user_id: The unique identifier of the user. 242 243 Returns: 244 Dictionary containing JSON response of the user. 245 """ 246 log_user(_log, user_id) 247 return await self.curl(self._user_endpoint(user_id), api_endpoint=False) 248 249 async def item( 250 self, item_id: str, fields: Optional[List[str]] = None 251 ) -> Dict[str, Any]: 252 """Read item metadata from the public item page (HTML), asynchronously. 253 254 The JSON item endpoint (``/api/v2/items/{id}/details``) is blocked by the 255 anti-bot protection and returns ``403`` (see 256 https://github.com/Giglium/vinted_scraper/issues/59), so the item data is 257 read from the public item page instead. Uses HTTP streaming to download 258 only the ``<head>`` section, extracting OpenGraph meta tags without 259 fetching the full page body. 260 261 Args: 262 item_id: The unique identifier of the item. 263 fields: List of ``OgField`` values to extract. Defaults to all 264 fields (``[OgField.TITLE, OgField.DESCRIPTION, OgField.URL, 265 OgField.IMAGE]``). 266 267 Returns: 268 A dict always containing ``id``, plus keys ``title``, 269 ``description``, ``url``, and ``image`` (each present only if 270 found and requested). 271 272 Raises: 273 RuntimeError: If the item page cannot be fetched (non-200 status). 274 """ 275 log_item(_log, item_id, fields) 276 endpoint = self._item_endpoint(item_id) 277 headers = self._build_page_headers() 278 279 head_html, response = await AsyncVintedWrapper._stream_until( 280 self._client, endpoint, headers, HEAD_END_TAG 281 ) 282 status_code = response.status_code 283 284 log_curl_response(_log, endpoint, status_code, response.headers, head_html) 285 286 if status_code == HTTP_OK: 287 return parse_item_page(item_id, head_html, fields) 288 289 self._raise_curl_error(endpoint, status_code) 290 291 async def curl( 292 self, 293 endpoint: str, 294 params: Optional[Dict] = None, 295 *, 296 api_endpoint: bool = False, 297 _retries: int = 0, 298 ) -> Dict[str, Any]: 299 """Send an async HTTP GET request to a relative Vinted API endpoint. 300 301 The ``endpoint`` is always relative and is concatenated with the chosen 302 client's ``base_url``: the ``api.`` host when ``api_endpoint`` is True, 303 otherwise the site (``www.``) host. Automatically handles headers, 304 cookies, retries, and error responses. 305 306 Args: 307 endpoint: Relative API endpoint path (e.g., "/api/v2/users/name"). 308 params: Optional query parameters. 309 api_endpoint: Route the request to the ``api.`` host instead of the 310 site host. 311 312 Returns: 313 Dictionary containing the parsed JSON response. 314 315 Raises: 316 RuntimeError: If response status is not 200 or JSON parsing fails. 317 """ 318 client = self._api_client if api_endpoint else self._client 319 headers = self._build_curl_headers() 320 log_curl_request(_log, str(client.base_url), endpoint, headers, params) 321 322 response = await client.get(endpoint, headers=headers, params=params) 323 324 log_curl_response( 325 _log, endpoint, response.status_code, response.headers, response.text 326 ) 327 328 if response.status_code == HTTP_OK: 329 return self._handle_curl_response(response, endpoint) 330 331 if response.status_code == HTTP_UNAUTHORIZED and _retries < DEFAULT_RETRIES: 332 log_cookie_retry(_log, response.status_code) 333 await self.refresh_session() 334 return await self.curl( 335 endpoint, params, api_endpoint=api_endpoint, _retries=_retries + 1 336 ) 337 338 self._raise_curl_error(endpoint, response.status_code) 339 340 async def __aenter__(self) -> "AsyncVintedWrapper": # pragma: no cover 341 """Enter async context manager. 342 343 Returns: 344 Self for use in async with statement. 345 """ 346 return self 347 348 async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: # pragma: no cover 349 """Exit async context manager and close both HTTP clients. 350 351 Args: 352 exc_type: Exception type (unused). 353 exc_val: Exception value (unused). 354 exc_tb: Exception traceback (unused). 355 """ 356 await self._client.aclose() 357 await self._api_client.aclose() 358 359 def __del__(self) -> None: # pragma: no cover 360 """Best-effort cleanup of the HTTP clients on garbage collection. 361 362 Prefer using the async context manager (``async with`` statement) 363 for deterministic resource cleanup. 364 365 Note: httpx.AsyncClient exposes ``aclose()`` (async) but not 366 ``close()`` (sync). Since ``__del__`` cannot await, we attempt a 367 synchronous close via the underlying transport if available. 368 """ 369 for attr in ("_client", "_api_client"): 370 client = getattr(self, attr, None) 371 if client is None or client.is_closed: 372 continue 373 try: 374 # httpx >=0.28 removed the sync close() helper on AsyncClient 375 client.close() # type: ignore[attr-defined] 376 except AttributeError: 377 # Fallback: close the underlying transport directly 378 transport = getattr(client, "_transport", None) 379 if transport is not None and hasattr(transport, "close"): 380 transport.close()
Asynchronous Vinted API wrapper returning raw JSON responses.
Handles cookie management, retries, and async HTTP requests automatically. Returns raw JSON dictionaries instead of typed objects.
Attributes:
baseurl: Vinted domain URL (e.g., "https://www.vinted.com").
session: API identity (VintedSession). Auto-fetched if None or empty.
user_agent: Custom user agent string. Auto-generated if None.
config: httpx client configuration dict.
cookie_names: List of cookie names to extract. Defaults to ["access_token_web"].
locale: Optional Locale override (e.g. "en-US"). Read from the
landing page when None, falling back to a guess from baseurl.
Example: See https://github.com/Giglium/vinted_scraper/blob/main/examples/async_wrapper.py
63 @classmethod 64 async def create( 65 cls, 66 baseurl: str, 67 user_agent: Optional[str] = None, 68 config: Optional[Dict] = None, 69 cookie_names: Optional[List[str]] = None, 70 session: Optional[VintedSession] = None, 71 locale: Optional[str] = None, 72 ): 73 """Factory method to create an AsyncVintedWrapper instance. 74 75 Use this instead of direct instantiation to automatically fetch the 76 session identity. Pass 77 ``session`` to reuse a prefetched one and skip the network fetch. 78 79 Args: 80 baseurl: Vinted domain URL (e.g., "https://www.vinted.com"). 81 user_agent: Custom user agent string. Auto-generated if None. 82 config: httpx client configuration dict. 83 cookie_names: List of cookie names to extract. Defaults to ["access_token_web"]. 84 session: A prefetched ``VintedSession``. Auto-fetched if None/empty. 85 locale: Optional ``Locale`` override. When None, the locale is read 86 from the landing page, falling back to a guess from ``baseurl``. 87 88 Returns: 89 Initialized AsyncVintedWrapper instance with a resolved session. 90 """ 91 _log.debug("Creating the async wrapper using the factory method") 92 self = cls( 93 baseurl, 94 session=session, 95 user_agent=user_agent, 96 config=config, 97 cookie_names=cookie_names, 98 locale=locale, 99 ) 100 if self._needs_session(): 101 await self.refresh_session() 102 return self
Factory method to create an AsyncVintedWrapper instance.
Use this instead of direct instantiation to automatically fetch the
session identity. Pass
session to reuse a prefetched one and skip the network fetch.
Args:
baseurl: Vinted domain URL (e.g., "https://www.vinted.com").
user_agent: Custom user agent string. Auto-generated if None.
config: httpx client configuration dict.
cookie_names: List of cookie names to extract. Defaults to ["access_token_web"].
session: A prefetched VintedSession. Auto-fetched if None/empty.
locale: Optional Locale override. When None, the locale is read
from the landing page, falling back to a guess from baseurl.
Returns: Initialized AsyncVintedWrapper instance with a resolved session.
121 async def refresh_session(self, retries: int = DEFAULT_RETRIES) -> VintedSession: 122 """Manually refresh the session cookie and API tokens. 123 124 Args: 125 retries: Number of retry attempts (default: 3). 126 127 Returns: 128 The ``VintedSession`` returned by :meth:`fetch_session`. 129 130 Raises: 131 RuntimeError: If cookies cannot be fetched after all retries. 132 """ 133 log_refresh_cookie(_log) 134 session = await AsyncVintedWrapper.fetch_session( 135 self._client, 136 self._get_cookie_headers(), 137 self.cookie_names, 138 retries, 139 ) 140 self.session = session 141 return session
Manually refresh the session cookie and API tokens.
Args: retries: Number of retry attempts (default: 3).
Returns:
The VintedSession returned by fetch_session().
Raises: RuntimeError: If cookies cannot be fetched after all retries.
143 @staticmethod 144 async def fetch_session( 145 client: httpx.AsyncClient, 146 headers: Dict, 147 cookie_names: List[str], 148 retries: int = DEFAULT_RETRIES, 149 ) -> VintedSession: 150 """Fetch the full session identity from Vinted's landing page (async). 151 152 Args: 153 client: httpx.AsyncClient instance. 154 headers: HTTP headers dictionary. 155 cookie_names: List of cookie names to extract. 156 retries: Number of retry attempts (default: 3). 157 158 Returns: 159 A ``VintedSession`` with the cookies, CSRF token and anonymous id. 160 161 Raises: 162 RuntimeError: If cookies cannot be fetched after all retries. 163 """ 164 response = None 165 166 for i in range(retries): 167 log_interaction(_log, i, retries) 168 html, response = await AsyncVintedWrapper._stream_until( 169 client, "/", headers, CSRF_MARKER 170 ) 171 172 if response.status_code == HTTP_OK: 173 session = build_session(response, html, cookie_names) 174 if session.is_usable(): 175 return session 176 177 sleep_time = handle_session_failure(response, i, retries) 178 if i < retries - 1: 179 await asyncio.sleep(sleep_time) 180 181 raise_session_error(client.base_url, response)
Fetch the full session identity from Vinted's landing page (async).
Args: client: httpx.AsyncClient instance. headers: HTTP headers dictionary. cookie_names: List of cookie names to extract. retries: Number of retry attempts (default: 3).
Returns:
A VintedSession with the cookies, CSRF token and anonymous id.
Raises: RuntimeError: If cookies cannot be fetched after all retries.
213 async def search(self, params: Optional[Dict] = None) -> Dict[str, Any]: 214 """Search for items on Vinted asynchronously. 215 216 Args: 217 params: Query parameters. Common parameters: 218 - search_text: Search query 219 - page: Page number 220 - per_page: Items per page 221 - price_from: Minimum price 222 - price_to: Maximum price 223 - order: Sort order 224 - attribute_ids[catalog]: Category IDs (comma-separated; 225 - attribute_ids[status]: Condition IDs (comma-separated; 226 - attribute_ids[brand]: Brand IDs (comma-separated; 227 - attribute_ids[size]: Size IDs (comma-separated; 228 229 Returns: 230 Dictionary containing JSON response with search results. 231 """ 232 log_search(_log, params) 233 return await self.curl( 234 self._search_endpoint(), params=params, api_endpoint=True 235 )
Search for items on Vinted asynchronously.
Args: params: Query parameters. Common parameters: - search_text: Search query - page: Page number - per_page: Items per page - price_from: Minimum price - price_to: Maximum price - order: Sort order - attribute_ids[catalog]: Category IDs (comma-separated; - attribute_ids[status]: Condition IDs (comma-separated; - attribute_ids[brand]: Brand IDs (comma-separated; - attribute_ids[size]: Size IDs (comma-separated;
Returns: Dictionary containing JSON response with search results.
237 async def get_user(self, user_id: Union[int, str]) -> Dict[str, Any]: 238 """Read a user's profile. 239 240 Args: 241 user_id: The unique identifier of the user. 242 243 Returns: 244 Dictionary containing JSON response of the user. 245 """ 246 log_user(_log, user_id) 247 return await self.curl(self._user_endpoint(user_id), api_endpoint=False)
Read a user's profile.
Args: user_id: The unique identifier of the user.
Returns: Dictionary containing JSON response of the user.
249 async def item( 250 self, item_id: str, fields: Optional[List[str]] = None 251 ) -> Dict[str, Any]: 252 """Read item metadata from the public item page (HTML), asynchronously. 253 254 The JSON item endpoint (``/api/v2/items/{id}/details``) is blocked by the 255 anti-bot protection and returns ``403`` (see 256 https://github.com/Giglium/vinted_scraper/issues/59), so the item data is 257 read from the public item page instead. Uses HTTP streaming to download 258 only the ``<head>`` section, extracting OpenGraph meta tags without 259 fetching the full page body. 260 261 Args: 262 item_id: The unique identifier of the item. 263 fields: List of ``OgField`` values to extract. Defaults to all 264 fields (``[OgField.TITLE, OgField.DESCRIPTION, OgField.URL, 265 OgField.IMAGE]``). 266 267 Returns: 268 A dict always containing ``id``, plus keys ``title``, 269 ``description``, ``url``, and ``image`` (each present only if 270 found and requested). 271 272 Raises: 273 RuntimeError: If the item page cannot be fetched (non-200 status). 274 """ 275 log_item(_log, item_id, fields) 276 endpoint = self._item_endpoint(item_id) 277 headers = self._build_page_headers() 278 279 head_html, response = await AsyncVintedWrapper._stream_until( 280 self._client, endpoint, headers, HEAD_END_TAG 281 ) 282 status_code = response.status_code 283 284 log_curl_response(_log, endpoint, status_code, response.headers, head_html) 285 286 if status_code == HTTP_OK: 287 return parse_item_page(item_id, head_html, fields) 288 289 self._raise_curl_error(endpoint, status_code)
Read item metadata from the public item page (HTML), asynchronously.
The JSON item endpoint (/api/v2/items/{id}/details) is blocked by the
anti-bot protection and returns 403 (see
https://github.com/Giglium/vinted_scraper/issues/59), so the item data is
read from the public item page instead. Uses HTTP streaming to download
only the <head> section, extracting OpenGraph meta tags without
fetching the full page body.
Args:
item_id: The unique identifier of the item.
fields: List of OgField values to extract. Defaults to all
fields ([OgField.TITLE, OgField.DESCRIPTION, OgField.URL,
OgField.IMAGE]).
Returns:
A dict always containing id, plus keys title,
description, url, and image (each present only if
found and requested).
Raises: RuntimeError: If the item page cannot be fetched (non-200 status).
291 async def curl( 292 self, 293 endpoint: str, 294 params: Optional[Dict] = None, 295 *, 296 api_endpoint: bool = False, 297 _retries: int = 0, 298 ) -> Dict[str, Any]: 299 """Send an async HTTP GET request to a relative Vinted API endpoint. 300 301 The ``endpoint`` is always relative and is concatenated with the chosen 302 client's ``base_url``: the ``api.`` host when ``api_endpoint`` is True, 303 otherwise the site (``www.``) host. Automatically handles headers, 304 cookies, retries, and error responses. 305 306 Args: 307 endpoint: Relative API endpoint path (e.g., "/api/v2/users/name"). 308 params: Optional query parameters. 309 api_endpoint: Route the request to the ``api.`` host instead of the 310 site host. 311 312 Returns: 313 Dictionary containing the parsed JSON response. 314 315 Raises: 316 RuntimeError: If response status is not 200 or JSON parsing fails. 317 """ 318 client = self._api_client if api_endpoint else self._client 319 headers = self._build_curl_headers() 320 log_curl_request(_log, str(client.base_url), endpoint, headers, params) 321 322 response = await client.get(endpoint, headers=headers, params=params) 323 324 log_curl_response( 325 _log, endpoint, response.status_code, response.headers, response.text 326 ) 327 328 if response.status_code == HTTP_OK: 329 return self._handle_curl_response(response, endpoint) 330 331 if response.status_code == HTTP_UNAUTHORIZED and _retries < DEFAULT_RETRIES: 332 log_cookie_retry(_log, response.status_code) 333 await self.refresh_session() 334 return await self.curl( 335 endpoint, params, api_endpoint=api_endpoint, _retries=_retries + 1 336 ) 337 338 self._raise_curl_error(endpoint, response.status_code)
Send an async HTTP GET request to a relative Vinted API endpoint.
The endpoint is always relative and is concatenated with the chosen
client's base_url: the api. host when api_endpoint is True,
otherwise the site (www.) host. Automatically handles headers,
cookies, retries, and error responses.
Args:
endpoint: Relative API endpoint path (e.g., "/api/v2/users/name").
params: Optional query parameters.
api_endpoint: Route the request to the api. host instead of the
site host.
Returns: Dictionary containing the parsed JSON response.
Raises: RuntimeError: If response status is not 200 or JSON parsing fails.
40@dataclass 41class VintedWrapper(BaseVintedWrapper): 42 """Synchronous Vinted API wrapper returning raw JSON responses. 43 44 Handles cookie management, retries, and HTTP requests automatically. 45 Returns raw JSON dictionaries instead of typed objects. 46 47 Attributes: 48 baseurl: Vinted domain URL (e.g., "https://www.vinted.com"). 49 session: API identity (VintedSession). Auto-fetched if None or empty. 50 user_agent: Custom user agent string. Auto-generated if None. 51 config: httpx client configuration dict. 52 cookie_names: List of cookie names to extract. Defaults to ["access_token_web"]. 53 locale: Optional ``Locale`` override (e.g. "en-US"). Read from the 54 landing page when None, falling back to a guess from ``baseurl``. 55 56 Example: 57 See https://github.com/Giglium/vinted_scraper/blob/main/examples/wrapper.py 58 """ 59 60 _client: httpx.Client = field(init=False, repr=False) 61 _api_client: httpx.Client = field(init=False, repr=False) 62 63 def __post_init__(self) -> None: 64 """Initialize VintedWrapper after dataclass initialization. 65 66 Validates the base URL, sets up user agent, initializes the two httpx 67 clients (site host and ``api.`` host), and fetches the session identity 68 (cookie + tokens) when none of its parts were provided. 69 70 Raises: 71 RuntimeError: If the base URL is invalid. 72 """ 73 site_config, api_config = self._validate_and_init() 74 self._client = httpx.Client(**site_config) 75 self._api_client = httpx.Client(**api_config) 76 if self._needs_session(): 77 self.refresh_session() 78 79 def refresh_session(self, retries: int = DEFAULT_RETRIES) -> VintedSession: 80 """Manually refresh the session cookie and API tokens. 81 82 Args: 83 retries: Number of retry attempts (default: 3). 84 85 Returns: 86 The ``VintedSession`` returned by :meth:`fetch_session`. 87 88 Raises: 89 RuntimeError: If cookies cannot be fetched after all retries. 90 """ 91 log_refresh_cookie(_log) 92 session = VintedWrapper.fetch_session( 93 self._client, 94 self._get_cookie_headers(), 95 self.cookie_names, 96 retries, 97 ) 98 self.session = session 99 return session 100 101 @staticmethod 102 def fetch_session( 103 client: httpx.Client, 104 headers: Dict, 105 cookie_names: List[str], 106 retries: int = DEFAULT_RETRIES, 107 ) -> VintedSession: 108 """Fetch the full session identity from Vinted's landing page. 109 110 Args: 111 client: httpx.Client instance. 112 headers: HTTP headers dictionary. 113 cookie_names: List of cookie names to extract. 114 retries: Number of retry attempts (default: 3). 115 116 Returns: 117 A ``VintedSession`` with the cookies, CSRF token and anonymous id. 118 119 Raises: 120 RuntimeError: If cookies cannot be fetched after all retries. 121 """ 122 response = None 123 124 for i in range(retries): 125 log_interaction(_log, i, retries) 126 html, response = VintedWrapper._stream_until( 127 client, "/", headers, CSRF_MARKER 128 ) 129 130 if response.status_code == HTTP_OK: 131 session = build_session(response, html, cookie_names) 132 if session.is_usable(): 133 return session 134 135 sleep_time = handle_session_failure(response, i, retries) 136 if i < retries - 1: 137 time.sleep(sleep_time) 138 139 raise_session_error(client.base_url, response) 140 141 @staticmethod 142 def _stream_until( 143 client: httpx.Client, url: str, headers: Dict, stop_marker: str 144 ) -> Tuple[str, httpx.Response]: 145 """Stream ``url``, reading only up to ``stop_marker``. 146 147 Shared by :meth:`item` (stops at ``</head>``) and the session fetch 148 (stops at the CSRF marker) so that neither downloads the full page body. 149 The chunk-boundary bookkeeping lives in :class:`ChunkAccumulator`. 150 151 Args: 152 client: httpx.Client instance. 153 url: The URL or endpoint path to request. 154 headers: Request headers for the GET. 155 stop_marker: The text marker that ends the read. 156 157 Returns: 158 Tuple of ``(html, response)``. ``html`` is empty for non-200 159 responses. 160 """ 161 acc = ChunkAccumulator(stop_marker) 162 with client.stream("GET", url, headers=headers) as response: 163 if response.status_code == HTTP_OK: 164 for chunk in response.iter_text(chunk_size=STREAM_CHUNK_SIZE): 165 if acc.add(chunk): 166 break 167 else: 168 response.read() 169 return acc.text, response 170 171 def search(self, params: Optional[Dict] = None) -> Dict[str, Any]: 172 """Search for items on Vinted. 173 174 Args: 175 params: Query parameters. Common parameters: 176 - search_text (str): Search query 177 - page (int): Page number 178 - per_page (int): Items per page 179 - price_from (float): Minimum price 180 - price_to (float): Maximum price 181 - order (str): Sort order 182 - attribute_ids[catalog] (str): Category IDs (comma-separated; 183 - attribute_ids[status] (str): Condition IDs (comma-separated; 184 - attribute_ids[brand] (str): Brand IDs (comma-separated; 185 - attribute_ids[size] (str): Size IDs (comma-separated; 186 187 Returns: 188 Dictionary containing JSON response with search results. 189 """ 190 log_search(_log, params) 191 return self.curl(self._search_endpoint(), params=params, api_endpoint=True) 192 193 def get_user(self, user_id: Union[int, str]) -> Dict[str, Any]: 194 """Read a user's profile. 195 196 Args: 197 user_id: The unique identifier of the user. 198 199 Returns: 200 Dictionary containing JSON response of the user. 201 """ 202 log_user(_log, user_id) 203 return self.curl(self._user_endpoint(user_id), api_endpoint=False) 204 205 def item(self, item_id: str, fields: Optional[List[str]] = None) -> Dict[str, Any]: 206 """Read item metadata from the public item page (HTML). 207 208 The JSON item endpoint (``/api/v2/items/{id}/details``) is blocked by the 209 anti-bot protection and returns ``403`` (see 210 https://github.com/Giglium/vinted_scraper/issues/59), so the item data is 211 read from the public item page instead. Uses HTTP streaming to download 212 only the ``<head>`` section, extracting OpenGraph meta tags without 213 fetching the full page body. 214 215 Args: 216 item_id: The unique identifier of the item. 217 fields: List of ``OgField`` values to extract. Defaults to all 218 fields (``[OgField.TITLE, OgField.DESCRIPTION, OgField.URL, 219 OgField.IMAGE]``). 220 221 Returns: 222 A dict always containing ``id``, plus keys ``title``, 223 ``description``, ``url``, and ``image`` (each present only if 224 found and requested). 225 226 Raises: 227 RuntimeError: If the item page cannot be fetched (non-200 status). 228 """ 229 log_item(_log, item_id, fields) 230 endpoint = self._item_endpoint(item_id) 231 headers = self._build_page_headers() 232 233 head_html, response = VintedWrapper._stream_until( 234 self._client, endpoint, headers, HEAD_END_TAG 235 ) 236 status_code = response.status_code 237 238 log_curl_response(_log, endpoint, status_code, response.headers, head_html) 239 240 if status_code == HTTP_OK: 241 return parse_item_page(item_id, head_html, fields) 242 243 self._raise_curl_error(endpoint, status_code) 244 245 def curl( 246 self, 247 endpoint: str, 248 params: Optional[Dict] = None, 249 *, 250 api_endpoint: bool = False, 251 _retries: int = 0, 252 ) -> Dict[str, Any]: 253 """Send a custom HTTP GET request to a relative Vinted API endpoint. 254 255 The ``endpoint`` is always relative and is concatenated with the chosen 256 client's ``base_url``: the ``api.`` host when ``api_endpoint`` is True, 257 otherwise the site (``www.``) host. Automatically handles headers, 258 cookies, retries, and error responses. 259 260 Args: 261 endpoint: Relative API endpoint path (e.g., "/api/v2/users/name"). 262 params: Optional query parameters. 263 api_endpoint: Route the request to the ``api.`` host instead of the 264 site host. 265 266 Returns: 267 Dictionary containing the parsed JSON response. 268 269 Raises: 270 RuntimeError: If response status is not 200 or JSON parsing fails. 271 """ 272 client = self._api_client if api_endpoint else self._client 273 headers = self._build_curl_headers() 274 log_curl_request(_log, str(client.base_url), endpoint, headers, params) 275 276 response = client.get(endpoint, headers=headers, params=params) 277 278 log_curl_response( 279 _log, endpoint, response.status_code, response.headers, response.text 280 ) 281 282 if response.status_code == HTTP_OK: 283 return self._handle_curl_response(response, endpoint) 284 285 if response.status_code == HTTP_UNAUTHORIZED and _retries < DEFAULT_RETRIES: 286 log_cookie_retry(_log, response.status_code) 287 self.refresh_session() 288 return self.curl( 289 endpoint, params, api_endpoint=api_endpoint, _retries=_retries + 1 290 ) 291 292 self._raise_curl_error(endpoint, response.status_code) 293 294 def __enter__(self) -> "VintedWrapper": 295 """Enter context manager. 296 297 Returns: 298 Self for use in with statement. 299 """ 300 return self 301 302 def __exit__(self, exc_type, exc_val, exc_tb) -> None: # pragma: no cover 303 """Exit context manager and close both HTTP clients. 304 305 Args: 306 exc_type: Exception type (unused). 307 exc_val: Exception value (unused). 308 exc_tb: Exception traceback (unused). 309 """ 310 self._client.close() 311 self._api_client.close() 312 313 def __del__(self) -> None: # pragma: no cover 314 """Best-effort cleanup of the HTTP clients on garbage collection. 315 316 Prefer using the context manager (``with`` statement) for 317 deterministic resource cleanup. 318 """ 319 for attr in ("_client", "_api_client"): 320 client = getattr(self, attr, None) 321 if client is not None and not client.is_closed: 322 client.close()
Synchronous Vinted API wrapper returning raw JSON responses.
Handles cookie management, retries, and HTTP requests automatically. Returns raw JSON dictionaries instead of typed objects.
Attributes:
baseurl: Vinted domain URL (e.g., "https://www.vinted.com").
session: API identity (VintedSession). Auto-fetched if None or empty.
user_agent: Custom user agent string. Auto-generated if None.
config: httpx client configuration dict.
cookie_names: List of cookie names to extract. Defaults to ["access_token_web"].
locale: Optional Locale override (e.g. "en-US"). Read from the
landing page when None, falling back to a guess from baseurl.
Example: See https://github.com/Giglium/vinted_scraper/blob/main/examples/wrapper.py
79 def refresh_session(self, retries: int = DEFAULT_RETRIES) -> VintedSession: 80 """Manually refresh the session cookie and API tokens. 81 82 Args: 83 retries: Number of retry attempts (default: 3). 84 85 Returns: 86 The ``VintedSession`` returned by :meth:`fetch_session`. 87 88 Raises: 89 RuntimeError: If cookies cannot be fetched after all retries. 90 """ 91 log_refresh_cookie(_log) 92 session = VintedWrapper.fetch_session( 93 self._client, 94 self._get_cookie_headers(), 95 self.cookie_names, 96 retries, 97 ) 98 self.session = session 99 return session
Manually refresh the session cookie and API tokens.
Args: retries: Number of retry attempts (default: 3).
Returns:
The VintedSession returned by fetch_session().
Raises: RuntimeError: If cookies cannot be fetched after all retries.
101 @staticmethod 102 def fetch_session( 103 client: httpx.Client, 104 headers: Dict, 105 cookie_names: List[str], 106 retries: int = DEFAULT_RETRIES, 107 ) -> VintedSession: 108 """Fetch the full session identity from Vinted's landing page. 109 110 Args: 111 client: httpx.Client instance. 112 headers: HTTP headers dictionary. 113 cookie_names: List of cookie names to extract. 114 retries: Number of retry attempts (default: 3). 115 116 Returns: 117 A ``VintedSession`` with the cookies, CSRF token and anonymous id. 118 119 Raises: 120 RuntimeError: If cookies cannot be fetched after all retries. 121 """ 122 response = None 123 124 for i in range(retries): 125 log_interaction(_log, i, retries) 126 html, response = VintedWrapper._stream_until( 127 client, "/", headers, CSRF_MARKER 128 ) 129 130 if response.status_code == HTTP_OK: 131 session = build_session(response, html, cookie_names) 132 if session.is_usable(): 133 return session 134 135 sleep_time = handle_session_failure(response, i, retries) 136 if i < retries - 1: 137 time.sleep(sleep_time) 138 139 raise_session_error(client.base_url, response)
Fetch the full session identity from Vinted's landing page.
Args: client: httpx.Client instance. headers: HTTP headers dictionary. cookie_names: List of cookie names to extract. retries: Number of retry attempts (default: 3).
Returns:
A VintedSession with the cookies, CSRF token and anonymous id.
Raises: RuntimeError: If cookies cannot be fetched after all retries.
171 def search(self, params: Optional[Dict] = None) -> Dict[str, Any]: 172 """Search for items on Vinted. 173 174 Args: 175 params: Query parameters. Common parameters: 176 - search_text (str): Search query 177 - page (int): Page number 178 - per_page (int): Items per page 179 - price_from (float): Minimum price 180 - price_to (float): Maximum price 181 - order (str): Sort order 182 - attribute_ids[catalog] (str): Category IDs (comma-separated; 183 - attribute_ids[status] (str): Condition IDs (comma-separated; 184 - attribute_ids[brand] (str): Brand IDs (comma-separated; 185 - attribute_ids[size] (str): Size IDs (comma-separated; 186 187 Returns: 188 Dictionary containing JSON response with search results. 189 """ 190 log_search(_log, params) 191 return self.curl(self._search_endpoint(), params=params, api_endpoint=True)
Search for items on Vinted.
Args: params: Query parameters. Common parameters: - search_text (str): Search query - page (int): Page number - per_page (int): Items per page - price_from (float): Minimum price - price_to (float): Maximum price - order (str): Sort order - attribute_ids[catalog] (str): Category IDs (comma-separated; - attribute_ids[status] (str): Condition IDs (comma-separated; - attribute_ids[brand] (str): Brand IDs (comma-separated; - attribute_ids[size] (str): Size IDs (comma-separated;
Returns: Dictionary containing JSON response with search results.
193 def get_user(self, user_id: Union[int, str]) -> Dict[str, Any]: 194 """Read a user's profile. 195 196 Args: 197 user_id: The unique identifier of the user. 198 199 Returns: 200 Dictionary containing JSON response of the user. 201 """ 202 log_user(_log, user_id) 203 return self.curl(self._user_endpoint(user_id), api_endpoint=False)
Read a user's profile.
Args: user_id: The unique identifier of the user.
Returns: Dictionary containing JSON response of the user.
205 def item(self, item_id: str, fields: Optional[List[str]] = None) -> Dict[str, Any]: 206 """Read item metadata from the public item page (HTML). 207 208 The JSON item endpoint (``/api/v2/items/{id}/details``) is blocked by the 209 anti-bot protection and returns ``403`` (see 210 https://github.com/Giglium/vinted_scraper/issues/59), so the item data is 211 read from the public item page instead. Uses HTTP streaming to download 212 only the ``<head>`` section, extracting OpenGraph meta tags without 213 fetching the full page body. 214 215 Args: 216 item_id: The unique identifier of the item. 217 fields: List of ``OgField`` values to extract. Defaults to all 218 fields (``[OgField.TITLE, OgField.DESCRIPTION, OgField.URL, 219 OgField.IMAGE]``). 220 221 Returns: 222 A dict always containing ``id``, plus keys ``title``, 223 ``description``, ``url``, and ``image`` (each present only if 224 found and requested). 225 226 Raises: 227 RuntimeError: If the item page cannot be fetched (non-200 status). 228 """ 229 log_item(_log, item_id, fields) 230 endpoint = self._item_endpoint(item_id) 231 headers = self._build_page_headers() 232 233 head_html, response = VintedWrapper._stream_until( 234 self._client, endpoint, headers, HEAD_END_TAG 235 ) 236 status_code = response.status_code 237 238 log_curl_response(_log, endpoint, status_code, response.headers, head_html) 239 240 if status_code == HTTP_OK: 241 return parse_item_page(item_id, head_html, fields) 242 243 self._raise_curl_error(endpoint, status_code)
Read item metadata from the public item page (HTML).
The JSON item endpoint (/api/v2/items/{id}/details) is blocked by the
anti-bot protection and returns 403 (see
https://github.com/Giglium/vinted_scraper/issues/59), so the item data is
read from the public item page instead. Uses HTTP streaming to download
only the <head> section, extracting OpenGraph meta tags without
fetching the full page body.
Args:
item_id: The unique identifier of the item.
fields: List of OgField values to extract. Defaults to all
fields ([OgField.TITLE, OgField.DESCRIPTION, OgField.URL,
OgField.IMAGE]).
Returns:
A dict always containing id, plus keys title,
description, url, and image (each present only if
found and requested).
Raises: RuntimeError: If the item page cannot be fetched (non-200 status).
245 def curl( 246 self, 247 endpoint: str, 248 params: Optional[Dict] = None, 249 *, 250 api_endpoint: bool = False, 251 _retries: int = 0, 252 ) -> Dict[str, Any]: 253 """Send a custom HTTP GET request to a relative Vinted API endpoint. 254 255 The ``endpoint`` is always relative and is concatenated with the chosen 256 client's ``base_url``: the ``api.`` host when ``api_endpoint`` is True, 257 otherwise the site (``www.``) host. Automatically handles headers, 258 cookies, retries, and error responses. 259 260 Args: 261 endpoint: Relative API endpoint path (e.g., "/api/v2/users/name"). 262 params: Optional query parameters. 263 api_endpoint: Route the request to the ``api.`` host instead of the 264 site host. 265 266 Returns: 267 Dictionary containing the parsed JSON response. 268 269 Raises: 270 RuntimeError: If response status is not 200 or JSON parsing fails. 271 """ 272 client = self._api_client if api_endpoint else self._client 273 headers = self._build_curl_headers() 274 log_curl_request(_log, str(client.base_url), endpoint, headers, params) 275 276 response = client.get(endpoint, headers=headers, params=params) 277 278 log_curl_response( 279 _log, endpoint, response.status_code, response.headers, response.text 280 ) 281 282 if response.status_code == HTTP_OK: 283 return self._handle_curl_response(response, endpoint) 284 285 if response.status_code == HTTP_UNAUTHORIZED and _retries < DEFAULT_RETRIES: 286 log_cookie_retry(_log, response.status_code) 287 self.refresh_session() 288 return self.curl( 289 endpoint, params, api_endpoint=api_endpoint, _retries=_retries + 1 290 ) 291 292 self._raise_curl_error(endpoint, response.status_code)
Send a custom HTTP GET request to a relative Vinted API endpoint.
The endpoint is always relative and is concatenated with the chosen
client's base_url: the api. host when api_endpoint is True,
otherwise the site (www.) host. Automatically handles headers,
cookies, retries, and error responses.
Args:
endpoint: Relative API endpoint path (e.g., "/api/v2/users/name").
params: Optional query parameters.
api_endpoint: Route the request to the api. host instead of the
site host.
Returns: Dictionary containing the parsed JSON response.
Raises: RuntimeError: If response status is not 200 or JSON parsing fails.
15@dataclass 16class AsyncVintedScraper(AsyncVintedWrapper): 17 """Asynchronous Vinted scraper with typed model support. 18 19 Returns structured VintedItem objects instead of raw JSON dictionaries. 20 Inherits all functionality from AsyncVintedWrapper. 21 22 Example: 23 See https://github.com/Giglium/vinted_scraper/blob/main/examples/async_scraper.py 24 """ 25 26 async def search(self, params: Optional[Dict] = None) -> List[VintedItem]: 27 """Search for items on Vinted asynchronously. 28 29 Args: 30 params: Query parameters for the search. Common parameters: 31 - search_text: Search query 32 - page: Page number 33 - per_page: Items per page 34 - price_from: Minimum price 35 - price_to: Maximum price 36 - order: Sort order 37 - attribute_ids[catalog]: Category IDs (comma-separated; 38 - attribute_ids[status]: Condition IDs (comma-separated; 39 - attribute_ids[brand]: Brand IDs (comma-separated; 40 - attribute_ids[size]: Size IDs (comma-separated; 41 42 Returns: 43 List of VintedItem objects representing search results. 44 """ 45 response = await super().search(params) 46 return [VintedItem(json_data=item) for item in response["items"]] 47 48 async def item( 49 self, item_id: str, fields: Optional[List[str]] = None 50 ) -> VintedItem: 51 """Read item metadata from the public item page (HTML), asynchronously. 52 53 The JSON item endpoint is blocked by the anti-bot protection and returns 54 ``403`` (see https://github.com/Giglium/vinted_scraper/issues/59), so the 55 data is read from the public item page instead. Only the fields exposed 56 by the page's OpenGraph tags are populated (``title``, ``description``, 57 ``url``, ``image``). 58 59 Args: 60 item_id: The unique identifier of the item. 61 fields: List of ``OgField`` values to extract. Defaults to all 62 fields (``[OgField.TITLE, OgField.DESCRIPTION, OgField.URL, 63 OgField.IMAGE]``). 64 65 Returns: 66 A VintedItem built from the page metadata. Always contains ``id``. 67 68 Raises: 69 RuntimeError: If the item page cannot be fetched (non-200 status). 70 """ 71 data = await super().item(item_id, fields) 72 return VintedItem(json_data=data) 73 74 async def get_user(self, user_id: Union[int, str]) -> VintedUser: 75 """Read a user's profile. 76 77 Args: 78 user_id: The unique identifier of the user. 79 80 Returns: 81 VintedUser built from the profile. 82 """ 83 return VintedUser(json_data=(await super().get_user(user_id))["user"]) 84 85 async def enrich(self, item: VintedItem) -> VintedItem: 86 """Enrich an existing VintedItem with description from the item page. 87 88 Fetches the ``og:description`` from the public item page and populates 89 the item's ``description`` attribute. Useful for enriching items 90 obtained from search results (which lack a full description). 91 92 Args: 93 item: A VintedItem to enrich (must have a valid ``id``). 94 95 Returns: 96 The same VintedItem instance with ``description`` populated. 97 98 Raises: 99 RuntimeError: If the item page cannot be fetched (non-200 status). 100 """ 101 data = await super().item(str(item.id), [OgField.DESCRIPTION]) 102 if OgField.DESCRIPTION in data: 103 item.description = data[OgField.DESCRIPTION] 104 return item 105 106 async def curl( 107 self, 108 endpoint: str, 109 params: Optional[Dict] = None, 110 *, 111 api_endpoint: bool = False, 112 _retries: int = 0, 113 ) -> VintedJsonModel: 114 """Send an async HTTP GET request to a relative Vinted API endpoint. 115 116 Args: 117 endpoint: The relative API endpoint path (e.g., "/api/v2/users/x"). 118 params: Optional query parameters. 119 api_endpoint: Route the request to the ``api.`` host instead of the 120 site host. 121 122 Returns: 123 VintedJsonModel containing the JSON response. 124 125 Raises: 126 RuntimeError: If the request fails or returns a non-200 status code. 127 """ 128 response = await super().curl( 129 endpoint, params, api_endpoint=api_endpoint, _retries=_retries 130 ) 131 return VintedJsonModel(json_data=response)
Asynchronous Vinted scraper with typed model support.
Returns structured VintedItem objects instead of raw JSON dictionaries. Inherits all functionality from AsyncVintedWrapper.
Example: See https://github.com/Giglium/vinted_scraper/blob/main/examples/async_scraper.py
26 async def search(self, params: Optional[Dict] = None) -> List[VintedItem]: 27 """Search for items on Vinted asynchronously. 28 29 Args: 30 params: Query parameters for the search. Common parameters: 31 - search_text: Search query 32 - page: Page number 33 - per_page: Items per page 34 - price_from: Minimum price 35 - price_to: Maximum price 36 - order: Sort order 37 - attribute_ids[catalog]: Category IDs (comma-separated; 38 - attribute_ids[status]: Condition IDs (comma-separated; 39 - attribute_ids[brand]: Brand IDs (comma-separated; 40 - attribute_ids[size]: Size IDs (comma-separated; 41 42 Returns: 43 List of VintedItem objects representing search results. 44 """ 45 response = await super().search(params) 46 return [VintedItem(json_data=item) for item in response["items"]]
Search for items on Vinted asynchronously.
Args: params: Query parameters for the search. Common parameters: - search_text: Search query - page: Page number - per_page: Items per page - price_from: Minimum price - price_to: Maximum price - order: Sort order - attribute_ids[catalog]: Category IDs (comma-separated; - attribute_ids[status]: Condition IDs (comma-separated; - attribute_ids[brand]: Brand IDs (comma-separated; - attribute_ids[size]: Size IDs (comma-separated;
Returns: List of VintedItem objects representing search results.
48 async def item( 49 self, item_id: str, fields: Optional[List[str]] = None 50 ) -> VintedItem: 51 """Read item metadata from the public item page (HTML), asynchronously. 52 53 The JSON item endpoint is blocked by the anti-bot protection and returns 54 ``403`` (see https://github.com/Giglium/vinted_scraper/issues/59), so the 55 data is read from the public item page instead. Only the fields exposed 56 by the page's OpenGraph tags are populated (``title``, ``description``, 57 ``url``, ``image``). 58 59 Args: 60 item_id: The unique identifier of the item. 61 fields: List of ``OgField`` values to extract. Defaults to all 62 fields (``[OgField.TITLE, OgField.DESCRIPTION, OgField.URL, 63 OgField.IMAGE]``). 64 65 Returns: 66 A VintedItem built from the page metadata. Always contains ``id``. 67 68 Raises: 69 RuntimeError: If the item page cannot be fetched (non-200 status). 70 """ 71 data = await super().item(item_id, fields) 72 return VintedItem(json_data=data)
Read item metadata from the public item page (HTML), asynchronously.
The JSON item endpoint is blocked by the anti-bot protection and returns
403 (see https://github.com/Giglium/vinted_scraper/issues/59), so the
data is read from the public item page instead. Only the fields exposed
by the page's OpenGraph tags are populated (title, description,
url, image).
Args:
item_id: The unique identifier of the item.
fields: List of OgField values to extract. Defaults to all
fields ([OgField.TITLE, OgField.DESCRIPTION, OgField.URL,
OgField.IMAGE]).
Returns:
A VintedItem built from the page metadata. Always contains id.
Raises: RuntimeError: If the item page cannot be fetched (non-200 status).
74 async def get_user(self, user_id: Union[int, str]) -> VintedUser: 75 """Read a user's profile. 76 77 Args: 78 user_id: The unique identifier of the user. 79 80 Returns: 81 VintedUser built from the profile. 82 """ 83 return VintedUser(json_data=(await super().get_user(user_id))["user"])
Read a user's profile.
Args: user_id: The unique identifier of the user.
Returns: VintedUser built from the profile.
85 async def enrich(self, item: VintedItem) -> VintedItem: 86 """Enrich an existing VintedItem with description from the item page. 87 88 Fetches the ``og:description`` from the public item page and populates 89 the item's ``description`` attribute. Useful for enriching items 90 obtained from search results (which lack a full description). 91 92 Args: 93 item: A VintedItem to enrich (must have a valid ``id``). 94 95 Returns: 96 The same VintedItem instance with ``description`` populated. 97 98 Raises: 99 RuntimeError: If the item page cannot be fetched (non-200 status). 100 """ 101 data = await super().item(str(item.id), [OgField.DESCRIPTION]) 102 if OgField.DESCRIPTION in data: 103 item.description = data[OgField.DESCRIPTION] 104 return item
Enrich an existing VintedItem with description from the item page.
Fetches the og:description from the public item page and populates
the item's description attribute. Useful for enriching items
obtained from search results (which lack a full description).
Args:
item: A VintedItem to enrich (must have a valid id).
Returns:
The same VintedItem instance with description populated.
Raises: RuntimeError: If the item page cannot be fetched (non-200 status).
106 async def curl( 107 self, 108 endpoint: str, 109 params: Optional[Dict] = None, 110 *, 111 api_endpoint: bool = False, 112 _retries: int = 0, 113 ) -> VintedJsonModel: 114 """Send an async HTTP GET request to a relative Vinted API endpoint. 115 116 Args: 117 endpoint: The relative API endpoint path (e.g., "/api/v2/users/x"). 118 params: Optional query parameters. 119 api_endpoint: Route the request to the ``api.`` host instead of the 120 site host. 121 122 Returns: 123 VintedJsonModel containing the JSON response. 124 125 Raises: 126 RuntimeError: If the request fails or returns a non-200 status code. 127 """ 128 response = await super().curl( 129 endpoint, params, api_endpoint=api_endpoint, _retries=_retries 130 ) 131 return VintedJsonModel(json_data=response)
Send an async HTTP GET request to a relative Vinted API endpoint.
Args:
endpoint: The relative API endpoint path (e.g., "/api/v2/users/x").
params: Optional query parameters.
api_endpoint: Route the request to the api. host instead of the
site host.
Returns: VintedJsonModel containing the JSON response.
Raises: RuntimeError: If the request fails or returns a non-200 status code.
15@dataclass 16class VintedScraper(VintedWrapper): 17 """Synchronous Vinted scraper with typed model support. 18 19 Returns structured VintedItem objects instead of raw JSON dictionaries. 20 Inherits all functionality from VintedWrapper. 21 22 Example: 23 See https://github.com/Giglium/vinted_scraper/blob/main/examples/scraper.py 24 """ 25 26 def search(self, params: Optional[Dict] = None) -> List[VintedItem]: # type: ignore 27 """Search for items on Vinted. 28 29 Args: 30 params: Query parameters for the search. Common parameters: 31 - search_text: Search query 32 - page: Page number 33 - per_page: Items per page 34 - price_from: Minimum price 35 - price_to: Maximum price 36 - order: Sort order 37 - attribute_ids[catalog]: Category IDs (comma-separated; 38 - attribute_ids[status]: Condition IDs (comma-separated; 39 - attribute_ids[brand]: Brand IDs (comma-separated; 40 - attribute_ids[size]: Size IDs (comma-separated; 41 42 Returns: 43 List of VintedItem objects representing search results. 44 """ 45 return [VintedItem(json_data=item) for item in super().search(params)["items"]] 46 47 def item( 48 self, item_id: str, fields: Optional[List[str]] = None 49 ) -> VintedItem: # type: ignore 50 """Read item metadata from the public item page (HTML). 51 52 The JSON item endpoint is blocked by the anti-bot protection and returns 53 ``403`` (see https://github.com/Giglium/vinted_scraper/issues/59), so the 54 data is read from the public item page instead. Only the fields exposed 55 by the page's OpenGraph tags are populated (``title``, ``description``, 56 ``url``, ``image``). 57 58 Args: 59 item_id: The unique identifier of the item. 60 fields: List of ``OgField`` values to extract. Defaults to all 61 fields (``[OgField.TITLE, OgField.DESCRIPTION, OgField.URL, 62 OgField.IMAGE]``). 63 64 Returns: 65 A VintedItem built from the page metadata. Always contains ``id``. 66 67 Raises: 68 RuntimeError: If the item page cannot be fetched (non-200 status). 69 """ 70 data = super().item(item_id, fields) 71 return VintedItem(json_data=data) 72 73 def get_user(self, user_id: Union[int, str]) -> VintedUser: 74 """Read a user's profile. 75 76 Args: 77 user_id: The unique identifier of the user. 78 79 Returns: 80 VintedUser built from the profile. 81 """ 82 return VintedUser(json_data=super().get_user(user_id)["user"]) 83 84 def enrich(self, item: VintedItem) -> VintedItem: 85 """Enrich an existing VintedItem with description from the item page. 86 87 Fetches the ``og:description`` from the public item page and populates 88 the item's ``description`` attribute. Useful for enriching items 89 obtained from search results (which lack a full description). 90 91 Args: 92 item: A VintedItem to enrich (must have a valid ``id``). 93 94 Returns: 95 The same VintedItem instance with ``description`` populated. 96 97 Raises: 98 RuntimeError: If the item page cannot be fetched (non-200 status). 99 """ 100 data = super().item(str(item.id), [OgField.DESCRIPTION]) 101 if OgField.DESCRIPTION in data: 102 item.description = data[OgField.DESCRIPTION] 103 return item 104 105 def curl( 106 self, 107 endpoint: str, 108 params: Optional[Dict] = None, 109 *, 110 api_endpoint: bool = False, 111 _retries: int = 0, 112 ) -> VintedJsonModel: # type: ignore 113 """Send a custom HTTP GET request to a relative Vinted API endpoint. 114 115 Args: 116 endpoint: The relative API endpoint path (e.g., "/api/v2/users/x"). 117 params: Optional query parameters. 118 api_endpoint: Route the request to the ``api.`` host instead of the 119 site host. 120 121 Returns: 122 VintedJsonModel containing the JSON response. 123 124 Raises: 125 RuntimeError: If the request fails or returns a non-200 status code. 126 """ 127 response = super().curl( 128 endpoint, params, api_endpoint=api_endpoint, _retries=_retries 129 ) 130 return VintedJsonModel(json_data=response)
Synchronous Vinted scraper with typed model support.
Returns structured VintedItem objects instead of raw JSON dictionaries. Inherits all functionality from VintedWrapper.
Example: See https://github.com/Giglium/vinted_scraper/blob/main/examples/scraper.py
26 def search(self, params: Optional[Dict] = None) -> List[VintedItem]: # type: ignore 27 """Search for items on Vinted. 28 29 Args: 30 params: Query parameters for the search. Common parameters: 31 - search_text: Search query 32 - page: Page number 33 - per_page: Items per page 34 - price_from: Minimum price 35 - price_to: Maximum price 36 - order: Sort order 37 - attribute_ids[catalog]: Category IDs (comma-separated; 38 - attribute_ids[status]: Condition IDs (comma-separated; 39 - attribute_ids[brand]: Brand IDs (comma-separated; 40 - attribute_ids[size]: Size IDs (comma-separated; 41 42 Returns: 43 List of VintedItem objects representing search results. 44 """ 45 return [VintedItem(json_data=item) for item in super().search(params)["items"]]
Search for items on Vinted.
Args: params: Query parameters for the search. Common parameters: - search_text: Search query - page: Page number - per_page: Items per page - price_from: Minimum price - price_to: Maximum price - order: Sort order - attribute_ids[catalog]: Category IDs (comma-separated; - attribute_ids[status]: Condition IDs (comma-separated; - attribute_ids[brand]: Brand IDs (comma-separated; - attribute_ids[size]: Size IDs (comma-separated;
Returns: List of VintedItem objects representing search results.
47 def item( 48 self, item_id: str, fields: Optional[List[str]] = None 49 ) -> VintedItem: # type: ignore 50 """Read item metadata from the public item page (HTML). 51 52 The JSON item endpoint is blocked by the anti-bot protection and returns 53 ``403`` (see https://github.com/Giglium/vinted_scraper/issues/59), so the 54 data is read from the public item page instead. Only the fields exposed 55 by the page's OpenGraph tags are populated (``title``, ``description``, 56 ``url``, ``image``). 57 58 Args: 59 item_id: The unique identifier of the item. 60 fields: List of ``OgField`` values to extract. Defaults to all 61 fields (``[OgField.TITLE, OgField.DESCRIPTION, OgField.URL, 62 OgField.IMAGE]``). 63 64 Returns: 65 A VintedItem built from the page metadata. Always contains ``id``. 66 67 Raises: 68 RuntimeError: If the item page cannot be fetched (non-200 status). 69 """ 70 data = super().item(item_id, fields) 71 return VintedItem(json_data=data)
Read item metadata from the public item page (HTML).
The JSON item endpoint is blocked by the anti-bot protection and returns
403 (see https://github.com/Giglium/vinted_scraper/issues/59), so the
data is read from the public item page instead. Only the fields exposed
by the page's OpenGraph tags are populated (title, description,
url, image).
Args:
item_id: The unique identifier of the item.
fields: List of OgField values to extract. Defaults to all
fields ([OgField.TITLE, OgField.DESCRIPTION, OgField.URL,
OgField.IMAGE]).
Returns:
A VintedItem built from the page metadata. Always contains id.
Raises: RuntimeError: If the item page cannot be fetched (non-200 status).
73 def get_user(self, user_id: Union[int, str]) -> VintedUser: 74 """Read a user's profile. 75 76 Args: 77 user_id: The unique identifier of the user. 78 79 Returns: 80 VintedUser built from the profile. 81 """ 82 return VintedUser(json_data=super().get_user(user_id)["user"])
Read a user's profile.
Args: user_id: The unique identifier of the user.
Returns: VintedUser built from the profile.
84 def enrich(self, item: VintedItem) -> VintedItem: 85 """Enrich an existing VintedItem with description from the item page. 86 87 Fetches the ``og:description`` from the public item page and populates 88 the item's ``description`` attribute. Useful for enriching items 89 obtained from search results (which lack a full description). 90 91 Args: 92 item: A VintedItem to enrich (must have a valid ``id``). 93 94 Returns: 95 The same VintedItem instance with ``description`` populated. 96 97 Raises: 98 RuntimeError: If the item page cannot be fetched (non-200 status). 99 """ 100 data = super().item(str(item.id), [OgField.DESCRIPTION]) 101 if OgField.DESCRIPTION in data: 102 item.description = data[OgField.DESCRIPTION] 103 return item
Enrich an existing VintedItem with description from the item page.
Fetches the og:description from the public item page and populates
the item's description attribute. Useful for enriching items
obtained from search results (which lack a full description).
Args:
item: A VintedItem to enrich (must have a valid id).
Returns:
The same VintedItem instance with description populated.
Raises: RuntimeError: If the item page cannot be fetched (non-200 status).
105 def curl( 106 self, 107 endpoint: str, 108 params: Optional[Dict] = None, 109 *, 110 api_endpoint: bool = False, 111 _retries: int = 0, 112 ) -> VintedJsonModel: # type: ignore 113 """Send a custom HTTP GET request to a relative Vinted API endpoint. 114 115 Args: 116 endpoint: The relative API endpoint path (e.g., "/api/v2/users/x"). 117 params: Optional query parameters. 118 api_endpoint: Route the request to the ``api.`` host instead of the 119 site host. 120 121 Returns: 122 VintedJsonModel containing the JSON response. 123 124 Raises: 125 RuntimeError: If the request fails or returns a non-200 status code. 126 """ 127 response = super().curl( 128 endpoint, params, api_endpoint=api_endpoint, _retries=_retries 129 ) 130 return VintedJsonModel(json_data=response)
Send a custom HTTP GET request to a relative Vinted API endpoint.
Args:
endpoint: The relative API endpoint path (e.g., "/api/v2/users/x").
params: Optional query parameters.
api_endpoint: Route the request to the api. host instead of the
site host.
Returns: VintedJsonModel containing the JSON response.
Raises: RuntimeError: If the request fails or returns a non-200 status code.
7class OgField(str, Enum): 8 """Available OpenGraph fields that can be extracted from an item page. 9 10 Members: 11 TITLE: The item title (derived from og:description). 12 DESCRIPTION: The full item description (og:description). 13 URL: The canonical item URL (og:url). 14 IMAGE: The item image URL (og:image). 15 """ 16 17 TITLE = "title" 18 DESCRIPTION = "description" 19 URL = "url" 20 IMAGE = "image"
Available OpenGraph fields that can be extracted from an item page.
Members: TITLE: The item title (derived from og:description). DESCRIPTION: The full item description (og:description). URL: The canonical item URL (og:url). IMAGE: The item image URL (og:image).
8@dataclass 9class VintedSession: 10 """The identity needed to authenticate Vinted API calls. 11 12 Bundles the values scraped from (or supplied for) the landing page: the 13 session ``cookies``, the ``anon_id`` returned as a response header, and the 14 ``csrf_token``. They are created, stored, and sent together, so they travel 15 as a single object. 16 17 The ``csrf_token`` is a supported field (it is sent when set and can be 18 supplied by a caller), but it is **not** auto-fetched from the landing page: 19 the API currently accepts calls without it. See 20 ``utils/_session.py::build_session`` for how to re-enable that. 21 22 Attributes: 23 cookies: Session cookies keyed by name. 24 csrf_token: CSRF token for the API, if available. Not auto-fetched. 25 anon_id: Anonymous id for the API, if available. 26 locale: Market locale tag (e.g. ``"cs-CZ"``) 27 """ 28 29 cookies: Dict[str, str] = field(default_factory=dict) 30 csrf_token: Optional[str] = None 31 anon_id: Optional[str] = None 32 locale: Optional[str] = None 33 34 def is_empty(self) -> bool: 35 """Return whether no identity part is set. 36 37 Returns: 38 ``True`` when there are no cookies and neither token is set. 39 """ 40 return not self.cookies and self.csrf_token is None and self.anon_id is None 41 42 def is_usable(self) -> bool: 43 """Return whether the session carries enough to authenticate a call. 44 45 A session is usable once the landing page has handed over the parts the 46 API actually checks: the session cookies and the anonymous id. The CSRF 47 token is sent when present but is not required to make the call (and is 48 not auto-fetched), so it is not part of this check. 49 50 Returns: 51 ``True`` when both cookies and an anonymous id are set. 52 """ 53 return bool(self.cookies) and self.anon_id is not None
The identity needed to authenticate Vinted API calls.
Bundles the values scraped from (or supplied for) the landing page: the
session cookies, the anon_id returned as a response header, and the
csrf_token. They are created, stored, and sent together, so they travel
as a single object.
The csrf_token is a supported field (it is sent when set and can be
supplied by a caller), but it is not auto-fetched from the landing page:
the API currently accepts calls without it. See
utils/_session.py::build_session for how to re-enable that.
Attributes:
cookies: Session cookies keyed by name.
csrf_token: CSRF token for the API, if available. Not auto-fetched.
anon_id: Anonymous id for the API, if available.
locale: Market locale tag (e.g. "cs-CZ")
34 def is_empty(self) -> bool: 35 """Return whether no identity part is set. 36 37 Returns: 38 ``True`` when there are no cookies and neither token is set. 39 """ 40 return not self.cookies and self.csrf_token is None and self.anon_id is None
Return whether no identity part is set.
Returns:
True when there are no cookies and neither token is set.
42 def is_usable(self) -> bool: 43 """Return whether the session carries enough to authenticate a call. 44 45 A session is usable once the landing page has handed over the parts the 46 API actually checks: the session cookies and the anonymous id. The CSRF 47 token is sent when present but is not required to make the call (and is 48 not auto-fetched), so it is not part of this check. 49 50 Returns: 51 ``True`` when both cookies and an anonymous id are set. 52 """ 53 return bool(self.cookies) and self.anon_id is not None
Return whether the session carries enough to authenticate a call.
A session is usable once the landing page has handed over the parts the API actually checks: the session cookies and the anonymous id. The CSRF token is sent when present but is not required to make the call (and is not auto-fetched), so it is not part of this check.
Returns:
True when both cookies and an anonymous id are set.