okej, ale chcialbym zachowac taki input schema: { "title": "Vinted API Scraper",…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
okej, ale chcialbym zachowac taki input schema: { "title": "Vinted API Scraper", "description": "Scrapes Vinted listings using API with anonymous token handling", "type": "object", "schemaVersion": 1, "properties": { "searchText": { "title": "Search term", "type": "string", "description": "e.g. oakley sunglasses", "default": "oakley sunglasses", "editor": "textfield" }, "proxyUrl": { "title": "Proxy URL", "type": "string", "description": "Proxy in format http://user:pass@host:port", "editor": "textfield" }, "totalItems": { "title": "Number of items to scrape", "type": "integer", "description": "e.g. 96, 150, 200 (96 = one full page)", "default": 96, "editor": "number" }, "sortBy": { "title": "Sort by", "type": "string", "description": "How to sort results?", "default": "relevance", "editor": "select", "enum": [ "relevance", "newest_first", "price_high_to_low", "price_low_to_high" ] }, "brand": { "title": "Brand (optional)", "type": "string", "description": "e.g. adidas, nike (leave empty to skip)", "editor": "textfield" }, "priceFrom": { "title": "Price from (optional)", "type": "string", "description": "Minimum price in local currency", "editor": "textfield" }, "priceTo": { "title": "Price to (optional)", "type": "string", "description": "Maximum price in local currency", "editor": "textfield" }, "region": { "title": "Region", "type": "string", "description": "Country/region of Vinted", "enum": [ "Poland", "France", "Germany", "Italy", "Belgium", "Spain", "Netherlands", "Austria", "Czechia", "Hungary", "Lithuania", "Slovakia", "Luxembourg", "Slovenia", "Finland", "Sweden", "Denmark", "Portugal", "Ireland", "Croatia" ], "default": "Poland" } }, "required": [ "searchText", "proxyUrl" ] } uwazam ze jest dobrze rozbudowany, wybor regionu w inputcie ulatwia skryptowi prace, nie trzeba robic zadnej geolokacji proxy itp.
Rozumiem, chcesz zachować dokładnie ten schemat wejściowy. Jest dobrze przemyślany. Oto zmodyfikowany kod main.js, który będzie działał z Twoim schematem:
import { Actor } from 'apify';
import { gotScraping } from 'got-scraping';
await Actor.init();
const input = await Actor.getInput();
const {
searchText,
proxyUrl,
totalItems = 96,
sortBy = 'relevance',
brand,
priceFrom,
priceTo,
region = 'Poland' // Domyślny region z schematu
} = input;
if (!searchText || !proxyUrl) {
throw new Error('Musisz podać "searchText" i "proxyUrl" w input.');
}
console.log(`🟢 [START] Używam proxy: ${proxyUrl}`);
console.log(`🌍 Region: ${region}`);
// Mapowanie regionów na kody domen Vinted
const regionToDomain = {
'Poland': 'pl',
'France': 'fr',
'Germany': 'de',
'Italy': 'it',
'Belgium': 'be',
'Spain': 'es',
'Netherlands': 'nl',
'Austria': 'at',
'Czechia': 'cz',
'Hungary': 'hu',
'Lithuania': 'lt',
'Slovakia': 'sk',
'Luxembourg': 'lu',
'Slovenia': 'si',
'Finland': 'fi',
'Sweden': 'se',
'Denmark': 'dk',
'Portugal': 'pt',
'Ireland': 'ie',
'Croatia': 'hr'
};
const regionCode = regionToDomain[region];
if (!regionCode) {
throw new Error(`Nieobsługiwany region: ${region}`);
}
const vintedDomain = `https://www.vinted.${regionCode}`;
const debugData = {
timestamp: new Date().toISOString(),
region: region,
regionCode: regionCode,
domain: vintedDomain,
tokenFetch: {},
headers: {},
itemsCount: 0,
itemsPreview: [],
errors: [],
rawHtmlSample: '',
rawJsonSample: ''
};
// 1. Pobieranie tokenów
async function getVintedTokens() {
try {
console.log(`🕵️♂️ Pobieram tokeny z ${vintedDomain}...`);
const response = await gotScraping({
url: vintedDomain,
proxyUrl,
headers: {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
'accept-language': `${regionCode}-${regionCode.toUpperCase()},${regionCode};q=0.9,en;q=0.8`,
}
});
debugData.rawHtmlSample = response.body.slice(0, 1000);
const cookies = response.headers['set-cookie'] || [];
const cookieHeader = cookies.map(c => c.split(';')[0]).join('; ');
const anonIdFromHeader = response.headers['x-anon-id'] || null;
const anonIdFromCookie = cookieHeader.match(/anon_id=([a-z0-9\-]+)/i)?.[1] || null;
const anonId = anonIdFromHeader || anonIdFromCookie;
console.log(`✅ Tokeny pobrane:`);
console.log(` • anonId: ${anonId}`);
console.log(` • cookieHeader: ${cookieHeader.slice(0, 80)}...`);
return { cookieHeader, anonId };
} catch (err) {
debugData.errors.push(`Token fetch error: ${err.message}`);
console.error('❌ Błąd podczas pobierania tokenów!');
throw new Error(`Nie udało się pobrać tokenów z ${vintedDomain}: ${err.message}`);
}
}
const { cookieHeader, anonId } = await getVintedTokens();
debugData.tokenFetch = { cookieHeader, anonId };
// 2. Przygotowanie nagłówków
const headers = {
'accept': 'application/json',
'x-anonymous-id': anonId,
'x-money-object': 'true',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
'cookie': cookieHeader,
'accept-language': `${regionCode}-${regionCode.toUpperCase()},${regionCode};q=0.9,en;q=0.8`,
'referer': `${vintedDomain}/`,
'origin': vintedDomain,
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'sec-ch-ua': '"Chromium";v="114", "Google Chrome";v="114", "Not:A-Brand";v="99"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
};
debugData.headers = headers;
// 3. Pobieranie ogłoszeń z API
let items = [];
let page = 1;
let done = false;
while (!done) {
const apiUrl = new URL(`${vintedDomain}/api/v2/catalog/items`);
apiUrl.searchParams.set('search_text', searchText);
apiUrl.searchParams.set('per_page', '96');
apiUrl.searchParams.set('page', page.toString());
if (sortBy) apiUrl.searchParams.set('order', sortBy);
if (brand) apiUrl.searchParams.set('brand', brand);
if (priceFrom) apiUrl.searchParams.set('price_from', priceFrom);
if (priceTo) apiUrl.searchParams.set('price_to', priceTo);
console.log(`🌐 Wysyłam zapytanie do API (strona ${page}):\n ${apiUrl.toString()}`);
try {
const apiResponse = await gotScraping({
url: apiUrl.toString(),
method: 'GET',
headers,
proxyUrl,
responseType: 'json',
});
const data = apiResponse.body;
if (page === 1) debugData.rawJsonSample = JSON.stringify(data).slice(0, 1000);
if (data && data.items && Array.isArray(data.items)) {
const pageItems = data.items.length;
console.log(`📦 Znaleziono ${pageItems} przedmiotów na stronie ${page}`);
for (const item of data.items) {
const thumbnail = item.photo?.url || item.photos?.[0]?.url || null;
items.push({
tytuł: item.title,
cena: item.price || '',
waluta: item.currency || '',
thumbnail,
liczba_lajków: item.favourite_count || 0,
liczba_wyświetleń: item.view_count || 0,
link: `${vintedDomain}${item.path}`,
region: region,
id: item.id
});
if (items.length >= totalItems) {
done = true;
break;
}
}
// Jeśli na stronie jest mniej niż 96 przedmiotów, to koniec
if (pageItems < 96) {
console.log('📭 Osiągnięto koniec wyników');
break;
}
} else {
debugData.errors.push('Brak danych "items" w odpowiedzi API.');
console.warn('⚠️ Brak danych "items" w odpowiedzi API.');
break;
}
} catch (err) {
debugData.errors.push(`API request error: ${err.message}`);
console.error(`❌ Błąd API Vinted: ${err.message}`);
// Jeśli to pierwszy request i mamy błąd, może to być problem z regionem
if (page === 1) {
console.error(`🚫 Prawdopodobny problem z regionem ${region} lub proxy`);
}
break;
}
page++;
}
debugData.itemsCount = items.length;
debugData.itemsPreview = items.slice(0, 3);
console.log(`✅ Pobrano łącznie ${items.length} ogłoszeń z regionu ${region}.`);
// 4. Zapis danych
await Actor.pushData(items);
// 5. Zapis debug.json
await Actor.setValue('debug.json', debugData);
console.log('🏁 Zakończono działanie aktora.');
await Actor.exit();
Dynamiczna domena - zamiast hardkodowanego vinted.pl, używam vinted.${regionCode} bazując na wybranym regionie
Mapowanie regionów - przekształcam nazwy krajów (Poland, France) na kody domen (pl, fr)
Dynamiczne nagłówki - dostosowuję accept-language i referer do wybranego regionu
Dodatkowe informacje - w danych wyjściowych dodałem pole region i waluta dla lepszej identyfikacji
Lepsza obsługa błędów - dodałem informacje o regionie w debugowaniu
Origin header - dodałem nagłówek origin który może być wymagany przez niektóre regiony
Kod powinien teraz działać dla wszystkich 20 regionów zdefiniowanych w Twoim schemacie wejściowym. Pamiętaj, że proxy powinno być odpowiednie dla danego regionu - niektóre regiony mogą blokować dostęp z innych krajów.