-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscraper.py
More file actions
220 lines (178 loc) · 6.53 KB
/
scraper.py
File metadata and controls
220 lines (178 loc) · 6.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""
Vinted scraper using ScrapingAnt API.
"""
import os
import time
from typing import List, Optional
import requests
from bs4 import BeautifulSoup
from config import (
SCRAPINGANT_API_URL,
SELECTORS,
DEFAULT_DELAY,
ITEMS_PER_PAGE
)
from models import VintedListing, ListingCollection
from utils import (
build_search_url,
parse_alt_text,
extract_item_id,
extract_favorites_count,
make_absolute_url
)
class VintedScraper:
"""Scraper for Vinted marketplace listings."""
def __init__(self, api_key: str, delay: float = DEFAULT_DELAY):
"""
Initialize the scraper.
Args:
api_key: ScrapingAnt API key
delay: Delay between requests in seconds
"""
self.api_key = api_key
self.delay = delay
self.collection = ListingCollection()
def _make_request(self, url: str) -> Optional[str]:
"""Make a request using ScrapingAnt API."""
params = {
"url": url,
"x-api-key": self.api_key,
"browser": "true",
"proxy_country": "US"
}
try:
response = requests.get(SCRAPINGANT_API_URL, params=params, timeout=120)
response.raise_for_status()
return response.text
except requests.RequestException as e:
print(f"Request failed for {url}: {e}")
return None
def _parse_listings(self, html: str, search_query: str = "", category: str = "") -> List[VintedListing]:
"""Parse listings from HTML content."""
soup = BeautifulSoup(html, 'html.parser')
listings = []
items = soup.select(SELECTORS["listing"])
for item in items:
try:
# Find the container with data-testid
container = item.select_one(SELECTORS["container"])
# Get link and URL
link_el = item.select_one(SELECTORS["link"])
if not link_el:
continue
url = link_el.get('href', '')
url = make_absolute_url(url)
# Get image and alt text with structured data
img_el = item.select_one(SELECTORS["image"])
if not img_el:
continue
alt_text = img_el.get('alt', '')
img_src = img_el.get('src', '')
# Parse structured data from alt text
parsed_data = parse_alt_text(alt_text)
# Extract item ID
item_id = extract_item_id(url)
if not item_id and container:
# Try from data-testid
test_id = container.get('data-testid', '')
if 'product-item-id-' in test_id:
item_id = test_id.replace('product-item-id-', '')
# Get favorites count
fav_btn = item.select_one(SELECTORS["favorites"])
favorites = 0
if fav_btn:
aria_label = fav_btn.get('aria-label', '')
favorites = extract_favorites_count(aria_label)
listing = VintedListing(
title=parsed_data["title"],
price=parsed_data["price"],
price_with_protection=parsed_data["price_with_protection"],
brand=parsed_data["brand"],
condition=parsed_data["condition"],
size=parsed_data["size"],
item_id=item_id,
listing_url=url,
image_url=img_src,
favorites_count=favorites,
category=category,
search_query=search_query
)
listings.append(listing)
except Exception as e:
print(f"Error parsing listing: {e}")
continue
return listings
def scrape_search(
self,
search_text: str = "",
category: str = "",
max_pages: int = 2,
min_price: Optional[float] = None,
max_price: Optional[float] = None
) -> int:
"""
Scrape listings from Vinted search results.
Args:
search_text: Search query
category: Category filter
max_pages: Maximum number of pages to scrape
min_price: Minimum price filter
max_price: Maximum price filter
Returns:
Number of listings scraped
"""
total_scraped = 0
for page in range(1, max_pages + 1):
url = build_search_url(
search_text=search_text,
category=category,
page=page,
min_price=min_price,
max_price=max_price
)
print(f"Scraping page {page}: {url}")
html = self._make_request(url)
if not html:
print(f"Failed to fetch page {page}")
continue
listings = self._parse_listings(html, search_query=search_text, category=category)
added = self.collection.add_many(listings)
print(f"Page {page}: scraped {len(listings)} listings, {added} new")
total_scraped += added
# Check if we got listings
if len(listings) == 0:
print("No more listings found, stopping pagination")
break
# Delay between requests
if page < max_pages:
time.sleep(self.delay)
return total_scraped
def scrape_categories(
self,
categories: List[str],
max_pages: int = 2
) -> int:
"""
Scrape multiple categories.
Args:
categories: List of category keys to scrape
max_pages: Maximum pages per category
Returns:
Total number of listings scraped
"""
total = 0
for category in categories:
print(f"\nScraping category: {category}")
count = self.scrape_search(category=category, max_pages=max_pages)
total += count
print(f"Category {category}: {count} listings")
return total
def get_results(self) -> ListingCollection:
"""Get the collection of scraped listings."""
return self.collection
def export_csv(self, filepath: str) -> None:
"""Export results to CSV."""
self.collection.to_csv(filepath)
def export_json(self, filepath: str) -> None:
"""Export results to JSON."""
self.collection.to_json(filepath)