discogs-marketplace-api-nodejs 1.15.0 → 1.16.0
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.
- package/README.MD +3 -0
- package/dist/scrapers/extractors/legacy.extractor.d.ts +11 -0
- package/dist/scrapers/extractors/legacy.extractor.js +138 -0
- package/dist/scrapers/legacy.scraper.d.ts +3 -1
- package/dist/scrapers/legacy.scraper.js +17 -144
- package/dist/scrapers/modern.scraper.d.ts +3 -1
- package/dist/scrapers/modern.scraper.js +18 -15
- package/dist/scrapers/wantlist.scraper.d.ts +3 -1
- package/dist/scrapers/wantlist.scraper.js +40 -38
- package/dist/search.js +46 -21
- package/package.json +4 -4
package/README.MD
CHANGED
|
@@ -9,6 +9,9 @@ A modern TypeScript/Node.js client for scraping and retrieving Discogs Marketpla
|
|
|
9
9
|
|
|
10
10
|
```sh
|
|
11
11
|
npm install discogs-marketplace-api-nodejs
|
|
12
|
+
|
|
13
|
+
# Because we use Playwright to scrape the data, you may also need to run:
|
|
14
|
+
# npx playwright install --with-deps chromium
|
|
12
15
|
```
|
|
13
16
|
|
|
14
17
|
## ⚡ Quick Start
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type SearchResult from '../../interfaces/search-result.interface.js';
|
|
2
|
+
/**
|
|
3
|
+
* Parses the page and returns the items found.
|
|
4
|
+
* @returns Items found and total
|
|
5
|
+
*/
|
|
6
|
+
export default function extractLegacy(): {
|
|
7
|
+
/** Items */
|
|
8
|
+
items: SearchResult['items'];
|
|
9
|
+
/** Total */
|
|
10
|
+
total: number;
|
|
11
|
+
};
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.default = extractLegacy;
|
|
4
|
+
// These variables are injected by the browser context when the page is loaded.
|
|
5
|
+
const { Country, Currency } = globalThis;
|
|
6
|
+
/**
|
|
7
|
+
* Parses the page and returns the items found.
|
|
8
|
+
* @returns Items found and total
|
|
9
|
+
*/
|
|
10
|
+
function extractLegacy() {
|
|
11
|
+
/**
|
|
12
|
+
* Converts a currency string to a standardized format.
|
|
13
|
+
* @param value String to clean
|
|
14
|
+
* @returns Cleaned-up string
|
|
15
|
+
*/
|
|
16
|
+
const convertCurrency = (value) => {
|
|
17
|
+
if (!value) {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
const currencyFound = Object.keys(Currency).find(key => value.includes(key));
|
|
21
|
+
if (!currencyFound) {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
const currencyClean = Currency[currencyFound];
|
|
25
|
+
const amount = value
|
|
26
|
+
.replace(currencyClean !== 'JPY' ? /[.](?=.*[.])/g : /\./g, '') // Remove all dots but the last, except for JPY
|
|
27
|
+
.replace(currencyFound, '') // Remove original currency
|
|
28
|
+
.replace(/\s\s+/g, ''); // Remove spaces
|
|
29
|
+
const amountParsed = currencyClean === 'JPY' ? Number.parseInt(amount) : Number.parseFloat(amount);
|
|
30
|
+
if (Number.isNaN(amountParsed)) {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
return currencyClean === 'JPY' ? `${amountParsed} ${currencyClean}` : `${amountParsed.toFixed(2)} ${currencyClean}`;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Safely parses a number from a string.
|
|
37
|
+
* @param value String to parse
|
|
38
|
+
* @returns Parsed number or 0 if invalid
|
|
39
|
+
*/
|
|
40
|
+
const safeParseInt = (value) => {
|
|
41
|
+
const parsed = Number.parseInt(value ?? '', 10);
|
|
42
|
+
return Number.isNaN(parsed) ? 0 : parsed;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Extracts and cleans text content from an element.
|
|
46
|
+
* @param selector CSS selector
|
|
47
|
+
* @param context Parent element to query from
|
|
48
|
+
* @returns Cleaned text content or an empty string
|
|
49
|
+
*/
|
|
50
|
+
const getTextContent = (selector, context = document) => context.querySelector(selector)?.textContent?.trim() ?? '';
|
|
51
|
+
const total = safeParseInt(getTextContent('.pagination_total')
|
|
52
|
+
.split(' ')
|
|
53
|
+
.filter(x => x)
|
|
54
|
+
.pop()
|
|
55
|
+
?.replace(/(,|\.|\s)/g, ''));
|
|
56
|
+
const items = [...document.querySelectorAll('table.table_block tbody tr')].map(el => {
|
|
57
|
+
const itemHref = el.querySelector('a.item_description_title')?.getAttribute('href') ?? '';
|
|
58
|
+
const mediaCondition = getTextContent('.item_condition span:nth-child(3)', el).split('\n')[0] ?? '';
|
|
59
|
+
const sleeveCondition = getTextContent('.item_condition span.item_sleeve_condition', el);
|
|
60
|
+
const countryName = getTextContent('.seller_info li:nth-child(3)', el).split(':').pop() ?? '';
|
|
61
|
+
const originalTitle = getTextContent('a.item_description_title', el);
|
|
62
|
+
const firstIndexOfDash = originalTitle.indexOf(' - ');
|
|
63
|
+
const lastIndexOfParenthesis = originalTitle.lastIndexOf(' (');
|
|
64
|
+
const releaseHref = el.querySelector('a.item_release_link')?.getAttribute('href') ?? '';
|
|
65
|
+
return {
|
|
66
|
+
id: safeParseInt(itemHref.split('/').pop()),
|
|
67
|
+
title: originalTitle,
|
|
68
|
+
artists: [
|
|
69
|
+
{
|
|
70
|
+
id: null,
|
|
71
|
+
name: firstIndexOfDash > -1 ? originalTitle.substring(0, firstIndexOfDash) : '',
|
|
72
|
+
url: null,
|
|
73
|
+
},
|
|
74
|
+
],
|
|
75
|
+
release: {
|
|
76
|
+
id: safeParseInt(releaseHref.split('release/').pop()?.split('-').shift()),
|
|
77
|
+
name: firstIndexOfDash > -1 && lastIndexOfParenthesis > -1
|
|
78
|
+
? originalTitle.substring(firstIndexOfDash + 3, lastIndexOfParenthesis)
|
|
79
|
+
: '',
|
|
80
|
+
url: `https://www.discogs.com${releaseHref}`,
|
|
81
|
+
},
|
|
82
|
+
formats: lastIndexOfParenthesis > -1
|
|
83
|
+
? originalTitle
|
|
84
|
+
.substring(lastIndexOfParenthesis + 2, originalTitle.length - 1)
|
|
85
|
+
.split(', ')
|
|
86
|
+
.filter(x => x)
|
|
87
|
+
: [],
|
|
88
|
+
labels: [...el.querySelectorAll(".label_and_cat a[href^='https://www.discogs.com/']")]
|
|
89
|
+
.map(x => ({
|
|
90
|
+
id: safeParseInt(x.getAttribute('href')?.split('label/').pop()?.split('-').shift()),
|
|
91
|
+
name: x.textContent?.trim() ?? '',
|
|
92
|
+
url: `https://www.discogs.com${x.getAttribute('href') ?? ''}`,
|
|
93
|
+
}))
|
|
94
|
+
.filter((value, index, self) => self.findIndex(v => v.name === value.name) === index),
|
|
95
|
+
url: `https://www.discogs.com${itemHref}`,
|
|
96
|
+
listedAt: null,
|
|
97
|
+
catnos: getTextContent('.label_and_cat .item_catno', el) // cspell:disable-line
|
|
98
|
+
.split(', ')
|
|
99
|
+
.filter(x => x !== 'none'),
|
|
100
|
+
imageUrl: el.querySelector('.marketplace_image')?.getAttribute('data-src') ?? null,
|
|
101
|
+
description: getTextContent('.item_condition + *', el) || null,
|
|
102
|
+
isAcceptingOffer: getTextContent('.item_add_to_cart p a strong', el).split('/').length > 1,
|
|
103
|
+
isAvailable: !el.classList.contains('unavailable'),
|
|
104
|
+
condition: {
|
|
105
|
+
media: {
|
|
106
|
+
full: mediaCondition,
|
|
107
|
+
short: /\(([^)]+)\)/.exec(mediaCondition)?.[1] ?? '',
|
|
108
|
+
},
|
|
109
|
+
sleeve: {
|
|
110
|
+
full: sleeveCondition || null,
|
|
111
|
+
short: /\(([^)]+)\)/.exec(sleeveCondition)?.[1] ?? null,
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
seller: {
|
|
115
|
+
name: getTextContent('.seller_info a', el),
|
|
116
|
+
url: `https://www.discogs.com${el.querySelector('.seller_info a')?.getAttribute('href') ?? ''}`,
|
|
117
|
+
score: getTextContent('.seller_info li:nth-child(2) strong', el) || null,
|
|
118
|
+
notes: safeParseInt(getTextContent('.seller_info li:nth-child(2) .section_link', el)) || null,
|
|
119
|
+
},
|
|
120
|
+
price: {
|
|
121
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
122
|
+
base: convertCurrency(getTextContent('.price', el).replace(/,/, '.')),
|
|
123
|
+
shipping: convertCurrency(getTextContent('.item_shipping', el)
|
|
124
|
+
.replace(/(\s+|\+)/g, ' ')
|
|
125
|
+
.replace(',', '.')),
|
|
126
|
+
},
|
|
127
|
+
country: {
|
|
128
|
+
name: countryName,
|
|
129
|
+
code: Country[countryName],
|
|
130
|
+
},
|
|
131
|
+
community: {
|
|
132
|
+
have: safeParseInt(getTextContent('.community_summary .community_result:nth-child(1) .community_number', el)),
|
|
133
|
+
want: safeParseInt(getTextContent('.community_summary .community_result:nth-child(2) .community_number', el)),
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
});
|
|
137
|
+
return { items, total };
|
|
138
|
+
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import type SearchResult from '../interfaces/search-result.interface.js';
|
|
2
2
|
import type { SearchParamsLegacy } from '../interfaces/search-params.interface.js';
|
|
3
|
+
import type { BrowserContext } from 'playwright-chromium';
|
|
3
4
|
/**
|
|
4
5
|
* Parses the page and returns the items found.
|
|
5
6
|
* @param url Url to scrape
|
|
7
|
+
* @param browserContext Playwright browser context
|
|
6
8
|
* @returns Items found and total
|
|
7
9
|
*/
|
|
8
|
-
export default function scrapeLegacy({ currency, genre, styles, formats, formatDescriptions, condition, years, isMakeAnOfferOnly, from, sort, limit, page, seller, lang, masterId, labelId, artistId, releaseId, user, query, }: SearchParamsLegacy): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
|
|
10
|
+
export default function scrapeLegacy({ currency, genre, styles, formats, formatDescriptions, condition, years, isMakeAnOfferOnly, from, sort, limit, page, seller, lang, masterId, labelId, artistId, releaseId, user, query, }: SearchParamsLegacy, browserContext: BrowserContext): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
|
|
9
11
|
/** Total items found */
|
|
10
12
|
total: SearchResult['result']['total'];
|
|
11
13
|
}>;
|
|
@@ -4,10 +4,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.default = scrapeLegacy;
|
|
7
|
-
const linkedom_1 = require("linkedom");
|
|
8
7
|
const currency_data_1 = __importDefault(require("../data/currency.data.js"));
|
|
9
8
|
const country_data_1 = __importDefault(require("../data/country.data.js"));
|
|
10
9
|
const search_1 = require("../search.js");
|
|
10
|
+
const legacy_extractor_1 = __importDefault(require("../scrapers/extractors/legacy.extractor.js"));
|
|
11
11
|
/**
|
|
12
12
|
* Generate URL to be parsed
|
|
13
13
|
* @returns Url
|
|
@@ -22,45 +22,13 @@ function generateUrl({ seller, lang, user, }) {
|
|
|
22
22
|
return `${baseUrl}/sell/list`;
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
|
-
/**
|
|
26
|
-
* Converts a currency string to a standardized format.
|
|
27
|
-
* @param value String to clean
|
|
28
|
-
* @returns Cleaned-up string
|
|
29
|
-
*/
|
|
30
|
-
function convertCurrency(value) {
|
|
31
|
-
if (!value) {
|
|
32
|
-
return null;
|
|
33
|
-
}
|
|
34
|
-
const currencyFound = Object.keys(currency_data_1.default).find(key => value.includes(key));
|
|
35
|
-
if (!currencyFound) {
|
|
36
|
-
return null;
|
|
37
|
-
}
|
|
38
|
-
const currencyClean = currency_data_1.default[currencyFound];
|
|
39
|
-
const amount = value
|
|
40
|
-
.replace(currencyClean !== 'JPY' ? /[.](?=.*[.])/g : /\./g, '') // Remove all dots but the last, except for JPY
|
|
41
|
-
.replace(currencyFound, '') // Remove original currency
|
|
42
|
-
.replace(/\s\s+/g, ''); // Remove spaces
|
|
43
|
-
const amountParsed = currencyClean === 'JPY' ? Number.parseInt(amount) : Number.parseFloat(amount);
|
|
44
|
-
if (Number.isNaN(amountParsed)) {
|
|
45
|
-
return null;
|
|
46
|
-
}
|
|
47
|
-
return currencyClean === 'JPY' ? `${amountParsed} ${currencyClean}` : `${amountParsed.toFixed(2)} ${currencyClean}`;
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Safely parses a number from a string.
|
|
51
|
-
* @param value String to parse
|
|
52
|
-
* @returns Parsed number or 0 if invalid
|
|
53
|
-
*/
|
|
54
|
-
function safeParseInt(value) {
|
|
55
|
-
const parsed = Number.parseInt(value ?? '', 10);
|
|
56
|
-
return Number.isNaN(parsed) ? 0 : parsed;
|
|
57
|
-
}
|
|
58
25
|
/**
|
|
59
26
|
* Parses the page and returns the items found.
|
|
60
27
|
* @param url Url to scrape
|
|
28
|
+
* @param browserContext Playwright browser context
|
|
61
29
|
* @returns Items found and total
|
|
62
30
|
*/
|
|
63
|
-
async function scrapeLegacy({ currency, genre, styles, formats, formatDescriptions, condition, years, isMakeAnOfferOnly = false, from, sort = search_1.DEFAULT_SORT, limit = search_1.DEFAULT_LIMIT, page = search_1.DEFAULT_PAGE, seller, lang = 'en', masterId, labelId, artistId, releaseId, user, query, }) {
|
|
31
|
+
async function scrapeLegacy({ currency, genre, styles, formats, formatDescriptions, condition, years, isMakeAnOfferOnly = false, from, sort = search_1.DEFAULT_SORT, limit = search_1.DEFAULT_LIMIT, page = search_1.DEFAULT_PAGE, seller, lang = 'en', masterId, labelId, artistId, releaseId, user, query, }, browserContext) {
|
|
64
32
|
/** Url to be called by the browser */
|
|
65
33
|
const urlGenerated = [
|
|
66
34
|
generateUrl({ seller, lang, user }),
|
|
@@ -86,117 +54,22 @@ async function scrapeLegacy({ currency, genre, styles, formats, formatDescriptio
|
|
|
86
54
|
['sort', sort],
|
|
87
55
|
].filter(([, p]) => !!p)).toString(),
|
|
88
56
|
].join('?');
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
headers,
|
|
99
|
-
referrer: 'https://discogs.com',
|
|
100
|
-
});
|
|
101
|
-
const content = await response.text();
|
|
102
|
-
const { document } = (0, linkedom_1.parseHTML)(content);
|
|
103
|
-
if (!response.ok) {
|
|
57
|
+
const browserPage = await browserContext.newPage();
|
|
58
|
+
await browserPage.route('**/*', route => (route.request().resourceType() === 'document' ? route.continue() : route.abort()));
|
|
59
|
+
// Inject some globals to the page, so we can use them in the scraping function
|
|
60
|
+
await browserPage.addInitScript(g => Object.assign(globalThis, g), { Country: country_data_1.default, Currency: currency_data_1.default });
|
|
61
|
+
const response = await browserPage.goto(urlGenerated);
|
|
62
|
+
// See current issue: https://github.com/evanw/esbuild/issues/2605
|
|
63
|
+
await browserPage.evaluate(() => (window.__name ??= (func) => func)); // eslint-disable-line
|
|
64
|
+
if (!response?.ok()) {
|
|
65
|
+
const errorMessage =
|
|
104
66
|
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
105
|
-
|
|
67
|
+
(await browserPage.evaluate(() => document.querySelector('h1 + p')?.innerHTML.trim())) ||
|
|
68
|
+
`An error ${response?.status() ?? '?'} occurred.`;
|
|
69
|
+
await browserPage.close();
|
|
106
70
|
throw new Error(errorMessage);
|
|
107
71
|
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
* @param selector CSS selector
|
|
111
|
-
* @param context Parent element to query from
|
|
112
|
-
* @returns Cleaned text content or an empty string
|
|
113
|
-
*/
|
|
114
|
-
const getTextContent = (selector, context = document) => context.querySelector(selector)?.textContent?.trim() ?? '';
|
|
115
|
-
const total = safeParseInt(getTextContent('.pagination_total')
|
|
116
|
-
.split(' ')
|
|
117
|
-
.filter(x => x)
|
|
118
|
-
.pop()
|
|
119
|
-
?.replace(/(,|\.|\s)/g, ''));
|
|
120
|
-
const items = [...document.querySelectorAll('table.table_block tbody tr')].map(el => {
|
|
121
|
-
const itemHref = el.querySelector('a.item_description_title')?.getAttribute('href') ?? '';
|
|
122
|
-
const mediaCondition = getTextContent('.item_condition span:nth-child(3)', el).split('\n')[0] ?? '';
|
|
123
|
-
const sleeveCondition = getTextContent('.item_condition span.item_sleeve_condition', el);
|
|
124
|
-
const countryName = getTextContent('.seller_info li:nth-child(3)', el).split(':').pop() ?? '';
|
|
125
|
-
const originalTitle = getTextContent('a.item_description_title', el);
|
|
126
|
-
const firstIndexOfDash = originalTitle.indexOf(' - ');
|
|
127
|
-
const lastIndexOfParenthesis = originalTitle.lastIndexOf(' (');
|
|
128
|
-
const releaseHref = el.querySelector('a.item_release_link')?.getAttribute('href') ?? '';
|
|
129
|
-
return {
|
|
130
|
-
id: safeParseInt(itemHref.split('/').pop()),
|
|
131
|
-
title: originalTitle,
|
|
132
|
-
artists: [
|
|
133
|
-
{
|
|
134
|
-
id: null,
|
|
135
|
-
name: firstIndexOfDash > -1 ? originalTitle.substring(0, firstIndexOfDash) : '',
|
|
136
|
-
url: null,
|
|
137
|
-
},
|
|
138
|
-
],
|
|
139
|
-
release: {
|
|
140
|
-
id: safeParseInt(releaseHref.split('release/').pop()?.split('-').shift()),
|
|
141
|
-
name: firstIndexOfDash > -1 && lastIndexOfParenthesis > -1
|
|
142
|
-
? originalTitle.substring(firstIndexOfDash + 3, lastIndexOfParenthesis)
|
|
143
|
-
: '',
|
|
144
|
-
url: `https://www.discogs.com${releaseHref}`,
|
|
145
|
-
},
|
|
146
|
-
formats: lastIndexOfParenthesis > -1
|
|
147
|
-
? originalTitle
|
|
148
|
-
.substring(lastIndexOfParenthesis + 2, originalTitle.length - 1)
|
|
149
|
-
.split(', ')
|
|
150
|
-
.filter(x => x)
|
|
151
|
-
: [],
|
|
152
|
-
labels: [...el.querySelectorAll(".label_and_cat a[href^='https://www.discogs.com/']")]
|
|
153
|
-
.map(x => ({
|
|
154
|
-
id: safeParseInt(x.getAttribute('href')?.split('label/').pop()?.split('-').shift()),
|
|
155
|
-
name: x.textContent?.trim() ?? '',
|
|
156
|
-
url: `https://www.discogs.com${x.getAttribute('href') ?? ''}`,
|
|
157
|
-
}))
|
|
158
|
-
.filter((value, index, self) => self.findIndex(v => v.name === value.name) === index),
|
|
159
|
-
url: `https://www.discogs.com${itemHref}`,
|
|
160
|
-
listedAt: null,
|
|
161
|
-
catnos: getTextContent('.label_and_cat .item_catno', el) // cspell:disable-line
|
|
162
|
-
.split(', ')
|
|
163
|
-
.filter(x => x !== 'none'),
|
|
164
|
-
imageUrl: el.querySelector('.marketplace_image')?.getAttribute('data-src') ?? null,
|
|
165
|
-
description: getTextContent('.item_condition + *', el) || null,
|
|
166
|
-
isAcceptingOffer: getTextContent('.item_add_to_cart p a strong', el).split('/').length > 1,
|
|
167
|
-
isAvailable: !el.classList.contains('unavailable'),
|
|
168
|
-
condition: {
|
|
169
|
-
media: {
|
|
170
|
-
full: mediaCondition,
|
|
171
|
-
short: /\(([^)]+)\)/.exec(mediaCondition)?.[1] ?? '',
|
|
172
|
-
},
|
|
173
|
-
sleeve: {
|
|
174
|
-
full: sleeveCondition || null,
|
|
175
|
-
short: /\(([^)]+)\)/.exec(sleeveCondition)?.[1] ?? null,
|
|
176
|
-
},
|
|
177
|
-
},
|
|
178
|
-
seller: {
|
|
179
|
-
name: getTextContent('.seller_info a', el),
|
|
180
|
-
url: `https://www.discogs.com${el.querySelector('.seller_info a')?.getAttribute('href') ?? ''}`,
|
|
181
|
-
score: getTextContent('.seller_info li:nth-child(2) strong', el) || null,
|
|
182
|
-
notes: safeParseInt(getTextContent('.seller_info li:nth-child(2) .section_link', el)) || null,
|
|
183
|
-
},
|
|
184
|
-
price: {
|
|
185
|
-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
186
|
-
base: convertCurrency(getTextContent('.price', el).replace(/,/, '.')),
|
|
187
|
-
shipping: convertCurrency(getTextContent('.item_shipping', el)
|
|
188
|
-
.replace(/(\s+|\+)/g, ' ')
|
|
189
|
-
.replace(',', '.')),
|
|
190
|
-
},
|
|
191
|
-
country: {
|
|
192
|
-
name: countryName,
|
|
193
|
-
code: country_data_1.default[countryName],
|
|
194
|
-
},
|
|
195
|
-
community: {
|
|
196
|
-
have: safeParseInt(getTextContent('.community_summary .community_result:nth-child(1) .community_number', el)),
|
|
197
|
-
want: safeParseInt(getTextContent('.community_summary .community_result:nth-child(2) .community_number', el)),
|
|
198
|
-
},
|
|
199
|
-
};
|
|
200
|
-
});
|
|
72
|
+
const { items, total } = await browserPage.evaluate(legacy_extractor_1.default);
|
|
73
|
+
await browserPage.close();
|
|
201
74
|
return { total, items, urlGenerated };
|
|
202
75
|
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import type SearchResult from '../interfaces/search-result.interface.js';
|
|
2
2
|
import type { SearchParamsModern } from '../interfaces/search-params.interface.js';
|
|
3
|
+
import type { BrowserContext } from 'playwright-chromium';
|
|
3
4
|
/**
|
|
4
5
|
* Parses the page and returns the items found.
|
|
5
6
|
* @param SearchParams Search parameters
|
|
7
|
+
* @param browserContext Playwright browser context
|
|
6
8
|
* @returns Items found and total
|
|
7
9
|
*/
|
|
8
|
-
export default function scrape({ currencies, genres, formats, formatDescriptions, conditions, years, isMakeAnOfferOnly, from, sort, limit, page, releaseIds, sellerIds, artistIds, priceRange, sellerRatingMin, hideGenericSleeves, hideSleevelessMedia, showUnavailable, sellerRatingCountMin, }: SearchParamsModern): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
|
|
10
|
+
export default function scrape({ currencies, genres, formats, formatDescriptions, conditions, years, isMakeAnOfferOnly, from, sort, limit, page, releaseIds, sellerIds, artistIds, priceRange, sellerRatingMin, hideGenericSleeves, hideSleevelessMedia, showUnavailable, sellerRatingCountMin, }: SearchParamsModern, browserContext: BrowserContext): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
|
|
9
11
|
/** Total items found */
|
|
10
12
|
total: SearchResult['result']['total'];
|
|
11
13
|
}>;
|
|
@@ -10,9 +10,10 @@ const search_1 = require("../search.js");
|
|
|
10
10
|
/**
|
|
11
11
|
* Parses the page and returns the items found.
|
|
12
12
|
* @param SearchParams Search parameters
|
|
13
|
+
* @param browserContext Playwright browser context
|
|
13
14
|
* @returns Items found and total
|
|
14
15
|
*/
|
|
15
|
-
async function scrape({ currencies, genres, formats, formatDescriptions, conditions, years, isMakeAnOfferOnly = false, from, sort = search_1.DEFAULT_SORT, limit = search_1.DEFAULT_LIMIT, page = search_1.DEFAULT_PAGE, releaseIds, sellerIds, artistIds, priceRange, sellerRatingMin = 0, hideGenericSleeves = false, hideSleevelessMedia = false, showUnavailable = true, sellerRatingCountMin = 0, }) {
|
|
16
|
+
async function scrape({ currencies, genres, formats, formatDescriptions, conditions, years, isMakeAnOfferOnly = false, from, sort = search_1.DEFAULT_SORT, limit = search_1.DEFAULT_LIMIT, page = search_1.DEFAULT_PAGE, releaseIds, sellerIds, artistIds, priceRange, sellerRatingMin = 0, hideGenericSleeves = false, hideSleevelessMedia = false, showUnavailable = true, sellerRatingCountMin = 0, }, browserContext) {
|
|
16
17
|
const [sortType, sortOrder] = sort.split(',');
|
|
17
18
|
const urlGenerated = [
|
|
18
19
|
'https://www.discogs.com/api/shop-page-api/sell_item',
|
|
@@ -62,29 +63,30 @@ async function scrape({ currencies, genres, formats, formatDescriptions, conditi
|
|
|
62
63
|
['priceRangeHigh', priceRange?.max.toString() ?? ''],
|
|
63
64
|
].filter(([, p]) => !!p)).toString(),
|
|
64
65
|
].join('?');
|
|
65
|
-
const
|
|
66
|
-
|
|
66
|
+
const browserPage = await browserContext.newPage();
|
|
67
|
+
const response = await browserPage.request.get(urlGenerated, {
|
|
67
68
|
headers: {
|
|
68
69
|
'User-Agent': 'Discogs',
|
|
69
70
|
'Content-Type': 'application/json',
|
|
71
|
+
Referrer: 'https://discogs.com',
|
|
70
72
|
},
|
|
71
|
-
referrer: 'https://discogs.com',
|
|
72
73
|
});
|
|
73
|
-
if (!response.ok) {
|
|
74
|
-
const message = response.headers
|
|
75
|
-
? (await response.json())
|
|
74
|
+
if (!response.ok()) {
|
|
75
|
+
const message = response.headers()['content-type']?.includes('application/json')
|
|
76
|
+
? (await response.json())?.detail
|
|
76
77
|
: '';
|
|
77
|
-
|
|
78
|
+
await browserPage.close();
|
|
79
|
+
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
|
80
|
+
throw new Error(message || `An error ${response.status()} occurred.`);
|
|
78
81
|
}
|
|
79
82
|
const result = (await response.json());
|
|
80
|
-
const detailsResponse = await
|
|
81
|
-
method: 'POST',
|
|
83
|
+
const detailsResponse = await browserPage.request.post('https://www.discogs.com/graphql', {
|
|
82
84
|
headers: {
|
|
83
85
|
'User-Agent': 'Discogs',
|
|
84
86
|
'Content-Type': 'application/json',
|
|
87
|
+
Referrer: 'https://discogs.com',
|
|
85
88
|
},
|
|
86
|
-
|
|
87
|
-
body: JSON.stringify({
|
|
89
|
+
data: {
|
|
88
90
|
// eslint-disable-next-line max-len
|
|
89
91
|
query: 'query Releases($discogsIds: [Int], $first: Int) {\n releases(discogsIds: $discogsIds) {\n inWantlistCount\n inCollectionCount\n images(first: $first) {\n edges {\n node {\n thumbnail {\n webpUrl\n }\n }\n }\n }\n ratings(first: 1) {\n averageRating\n }\n discogsId\n }\n}',
|
|
90
92
|
variables: {
|
|
@@ -97,12 +99,13 @@ async function scrape({ currencies, genres, formats, formatDescriptions, conditi
|
|
|
97
99
|
sha256Hash: 'ee9d48441023ebd1e6ca169e550581b45de216e88b40711acb6617e49e1bb0cb',
|
|
98
100
|
},
|
|
99
101
|
},
|
|
100
|
-
}
|
|
102
|
+
},
|
|
101
103
|
});
|
|
102
|
-
if (!detailsResponse.ok) {
|
|
103
|
-
throw new Error(
|
|
104
|
+
if (!detailsResponse.ok()) {
|
|
105
|
+
throw new Error(`An error ${detailsResponse.status()} occurred.`);
|
|
104
106
|
}
|
|
105
107
|
const detailsResult = (await detailsResponse.json());
|
|
108
|
+
await browserPage.close();
|
|
106
109
|
const details = Object.fromEntries(detailsResult.data?.releases?.map(release => {
|
|
107
110
|
if (!release?.discogsId) {
|
|
108
111
|
return [0, { imageUrl: null, want: 0, have: 0 }];
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import type SearchResult from '../interfaces/search-result.interface.js';
|
|
2
2
|
import type { SearchParamsModern } from '../interfaces/search-params.interface.js';
|
|
3
|
+
import type { BrowserContext } from 'playwright-chromium';
|
|
3
4
|
/**
|
|
4
5
|
* Parses the page and returns the items found.
|
|
5
6
|
* @param searchParams Search parameters
|
|
7
|
+
* @param browserContext Playwright browser context
|
|
6
8
|
* @returns Items found and total
|
|
7
9
|
*/
|
|
8
|
-
export default function scrapeWantlist(searchParams: SearchParamsModern): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
|
|
10
|
+
export default function scrapeWantlist(searchParams: SearchParamsModern, browserContext: BrowserContext): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
|
|
9
11
|
/** Total items found */
|
|
10
12
|
total: SearchResult['result']['total'];
|
|
11
13
|
}>;
|
|
@@ -4,54 +4,56 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.default = scrapeWantlist;
|
|
7
|
-
const linkedom_1 = require("linkedom");
|
|
8
7
|
const modern_scraper_1 = __importDefault(require("../scrapers/modern.scraper.js"));
|
|
9
8
|
const PER_PAGE = 250;
|
|
10
9
|
/**
|
|
11
10
|
* Parses the page and returns the items found.
|
|
12
11
|
* @param searchParams Search parameters
|
|
12
|
+
* @param browserContext Playwright browser context
|
|
13
13
|
* @returns Items found and total
|
|
14
14
|
*/
|
|
15
|
-
async function scrapeWantlist(searchParams) {
|
|
15
|
+
async function scrapeWantlist(searchParams, browserContext) {
|
|
16
|
+
/**
|
|
17
|
+
* Fetches the content of a specific page number in the wantlist.
|
|
18
|
+
* @param pageNumber Page number to fetch
|
|
19
|
+
* @returns Links and total items found
|
|
20
|
+
*/
|
|
21
|
+
const getPageContent = async (pageNumber) => {
|
|
22
|
+
const browserPage = await browserContext.newPage();
|
|
23
|
+
await browserPage.route('**/*', route => (route.request().resourceType() === 'document' ? route.continue() : route.abort()));
|
|
24
|
+
const response = await browserPage.goto(`https://www.discogs.com/wantlist?${new URLSearchParams({
|
|
25
|
+
page: pageNumber.toString(),
|
|
26
|
+
limit: PER_PAGE.toString(),
|
|
27
|
+
user: searchParams.wantlist ?? '',
|
|
28
|
+
layout: 'sm',
|
|
29
|
+
}).toString()}`);
|
|
30
|
+
const [total, ids] = await Promise.all([
|
|
31
|
+
browserPage.evaluate(() => +(document.querySelector('.pagination_total')?.textContent?.split(' of ').pop()?.replace(',', '') ?? '0')),
|
|
32
|
+
browserPage.evaluate(() => {
|
|
33
|
+
/** Extract the links to the items in the wantlist, if there's no link it's not for sale */
|
|
34
|
+
const links = [...document.querySelectorAll('.marketplace_for_sale_count a')];
|
|
35
|
+
return links.map(x => +(new URL(`https://discogs.com${x.href}`).pathname.split('/').pop() ?? '0'));
|
|
36
|
+
}),
|
|
37
|
+
]);
|
|
38
|
+
await browserPage.close();
|
|
39
|
+
return {
|
|
40
|
+
ids,
|
|
41
|
+
total,
|
|
42
|
+
status: response?.status() ?? 500,
|
|
43
|
+
};
|
|
44
|
+
};
|
|
16
45
|
/** Fetch the first page of user wantlist */
|
|
17
|
-
const firstPageResponse = await
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
user: searchParams.wantlist ?? '',
|
|
21
|
-
layout: 'sm',
|
|
22
|
-
}).toString()}`, {
|
|
23
|
-
headers: { 'User-Agent': 'Discogs', 'Content-Type': 'application/json' },
|
|
24
|
-
referrer: 'https://discogs.com',
|
|
25
|
-
});
|
|
26
|
-
if (!firstPageResponse.ok && firstPageResponse.status !== 404) {
|
|
27
|
-
throw new Error(firstPageResponse.statusText || `An error ${firstPageResponse.status} occurred.`);
|
|
46
|
+
const firstPageResponse = await getPageContent(1);
|
|
47
|
+
if (firstPageResponse.status >= 400 && firstPageResponse.status !== 404) {
|
|
48
|
+
throw new Error(`An error ${firstPageResponse.status} occurred.`);
|
|
28
49
|
}
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
const
|
|
33
|
-
const wants = await Promise.all(new Array(Math.ceil(total / PER_PAGE)).fill({}).map(async (_, i) => {
|
|
34
|
-
const page = i + 1;
|
|
35
|
-
const result = page === 1
|
|
36
|
-
? firstPage
|
|
37
|
-
: (await globalThis.fetch(`https://www.discogs.com/wantlist?${new URLSearchParams({
|
|
38
|
-
page: page.toString(),
|
|
39
|
-
limit: PER_PAGE.toString(),
|
|
40
|
-
user: searchParams.wantlist ?? '',
|
|
41
|
-
layout: 'sm',
|
|
42
|
-
}).toString()}`, {
|
|
43
|
-
headers: { 'User-Agent': 'Discogs', 'Content-Type': 'application/json' },
|
|
44
|
-
referrer: 'https://discogs.com',
|
|
45
|
-
})).text();
|
|
46
|
-
const { document } = (0, linkedom_1.parseHTML)(result);
|
|
47
|
-
/** Extract the links to the items in the wantlist, if there's no link it's not for sale */
|
|
48
|
-
const links = [...document.querySelectorAll('.marketplace_for_sale_count a')];
|
|
49
|
-
return links.map(x => +(new URL(`https://discogs.com${x.href}`).pathname.split('/').pop() ?? '0'));
|
|
50
|
-
}));
|
|
51
|
-
const wantlistIds = wants.flat();
|
|
50
|
+
const wants = await Promise.all(new Array(Math.ceil(firstPageResponse.total / PER_PAGE))
|
|
51
|
+
.fill({})
|
|
52
|
+
.map(async (_, i) => (i === 0 ? firstPageResponse : await getPageContent(i + 1))));
|
|
53
|
+
const wantlistIds = wants.flatMap(x => x.ids);
|
|
52
54
|
// If there's nothing for sale
|
|
53
55
|
if (wantlistIds.length === 0) {
|
|
54
|
-
return (0, modern_scraper_1.default)({ ...searchParams, releaseIds: [0], wantlist: undefined });
|
|
56
|
+
return (0, modern_scraper_1.default)({ ...searchParams, releaseIds: [0], wantlist: undefined }, browserContext);
|
|
55
57
|
}
|
|
56
|
-
return (0, modern_scraper_1.default)({ ...searchParams, releaseIds: wantlistIds, wantlist: undefined });
|
|
58
|
+
return (0, modern_scraper_1.default)({ ...searchParams, releaseIds: wantlistIds, wantlist: undefined }, browserContext);
|
|
57
59
|
}
|
package/dist/search.js
CHANGED
|
@@ -5,6 +5,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.DEFAULT_SORT = exports.DEFAULT_PAGE = exports.DEFAULT_LIMIT = void 0;
|
|
7
7
|
exports.default = search;
|
|
8
|
+
const playwright_extra_1 = require("playwright-extra");
|
|
9
|
+
const puppeteer_extra_plugin_stealth_1 = __importDefault(require("puppeteer-extra-plugin-stealth"));
|
|
8
10
|
const legacy_scraper_1 = __importDefault(require("./scrapers/legacy.scraper.js"));
|
|
9
11
|
const wantlist_scraper_1 = __importDefault(require("./scrapers/wantlist.scraper.js"));
|
|
10
12
|
const modern_scraper_1 = __importDefault(require("./scrapers/modern.scraper.js"));
|
|
@@ -17,25 +19,48 @@ exports.DEFAULT_SORT = 'listed,desc';
|
|
|
17
19
|
* @returns A promise that resolves to the search results, including items found, pagination details, and the generated URL.
|
|
18
20
|
*/
|
|
19
21
|
async function search(searchParams) {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
22
|
+
playwright_extra_1.chromium.use((0, puppeteer_extra_plugin_stealth_1.default)());
|
|
23
|
+
const browser = await playwright_extra_1.chromium.launch({
|
|
24
|
+
headless: true,
|
|
25
|
+
chromiumSandbox: false,
|
|
26
|
+
args: ['--no-sandbox', '--disable-setuid-sandbox'],
|
|
27
|
+
});
|
|
28
|
+
const browserContext = await browser.newContext({
|
|
29
|
+
javaScriptEnabled: false,
|
|
30
|
+
extraHTTPHeaders: searchParams.api === 'legacy' && !(searchParams.seller && searchParams.user)
|
|
31
|
+
? {
|
|
32
|
+
'X-PJAX': 'true',
|
|
33
|
+
}
|
|
34
|
+
: undefined,
|
|
35
|
+
});
|
|
36
|
+
try {
|
|
37
|
+
const { items, total, urlGenerated } = await (() => {
|
|
38
|
+
if (searchParams.api === 'v2' && searchParams.wantlist) {
|
|
39
|
+
return (0, wantlist_scraper_1.default)(searchParams, browserContext);
|
|
40
|
+
}
|
|
41
|
+
if (searchParams.api === 'v2') {
|
|
42
|
+
return (0, modern_scraper_1.default)(searchParams, browserContext);
|
|
43
|
+
}
|
|
44
|
+
return (0, legacy_scraper_1.default)(searchParams, browserContext);
|
|
45
|
+
})();
|
|
46
|
+
await browserContext.close();
|
|
47
|
+
await browser.close();
|
|
48
|
+
return {
|
|
49
|
+
items,
|
|
50
|
+
result: {
|
|
51
|
+
total,
|
|
52
|
+
perPage: searchParams.limit ?? exports.DEFAULT_LIMIT,
|
|
53
|
+
},
|
|
54
|
+
page: {
|
|
55
|
+
current: searchParams.page ?? exports.DEFAULT_PAGE,
|
|
56
|
+
total: Math.ceil(total / (searchParams.limit ?? exports.DEFAULT_LIMIT)),
|
|
57
|
+
},
|
|
58
|
+
urlGenerated,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
await browserContext.close();
|
|
63
|
+
await browser.close();
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
41
66
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "discogs-marketplace-api-nodejs",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.16.0",
|
|
4
4
|
"description": "Another (better ?) NodeJs library to fetch data from Discogs marketplace",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"discogs",
|
|
@@ -40,13 +40,13 @@
|
|
|
40
40
|
}
|
|
41
41
|
],
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"
|
|
44
|
-
"
|
|
43
|
+
"playwright-chromium": "^1.57.0",
|
|
44
|
+
"playwright-extra": "^4.3.6",
|
|
45
|
+
"puppeteer-extra-plugin-stealth": "^2.11.2"
|
|
45
46
|
},
|
|
46
47
|
"devDependencies": {
|
|
47
48
|
"@eslint/js": "^9.31.0",
|
|
48
49
|
"@types/node": "^20.19.8",
|
|
49
|
-
"@types/user-agents": "^1.0.4",
|
|
50
50
|
"@typescript-eslint/eslint-plugin": "^8.29.1",
|
|
51
51
|
"@typescript-eslint/parser": "^8.29.1",
|
|
52
52
|
"cspell": "^9.1.5",
|