1 | const axios = require('axios');
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | const search = async (query, ogq) => {
|
12 | const base = 'https://www.youtube.com/results';
|
13 |
|
14 | const options = {
|
15 | app: 'desktop',
|
16 | search_query: query
|
17 | };
|
18 |
|
19 | try {
|
20 | const response = await axios.get(base, { params: options });
|
21 | const html = response.data;
|
22 |
|
23 |
|
24 | const findInitialData = html.match(/var ytInitialData = {(.*?)};/g)[0];
|
25 | const fixData = findInitialData.replace(/var ytInitialData = /g, '');
|
26 | const initialData = JSON.parse(fixData.slice(0, -1));
|
27 |
|
28 |
|
29 | let data = initialData.contents.twoColumnSearchResultsRenderer.primaryContents.sectionListRenderer.contents;
|
30 | let index, confirm = false;
|
31 | for (let i = 0; i < data.length; i++) {
|
32 | if (confirm) break;
|
33 | if (data[i].hasOwnProperty('itemSectionRenderer')) {
|
34 | for (let j = 0; j < data[i].itemSectionRenderer.contents.length; j++) {
|
35 | if (data[i].itemSectionRenderer.contents[j].hasOwnProperty('videoRenderer')) {
|
36 | index = i;
|
37 | confirm = true;
|
38 | break;
|
39 | }
|
40 | }
|
41 | }
|
42 | }
|
43 |
|
44 |
|
45 | if (typeof data[index] === 'object' && data[index].hasOwnProperty('itemSectionRenderer')) {
|
46 | data = data[index].itemSectionRenderer.contents;
|
47 | return data;
|
48 | } else {
|
49 | throw new Error(`No results were found for search query '${ogq}'.`);
|
50 | }
|
51 | } catch (error) {
|
52 | throw new Error(`Error searching for query '${ogq}': ${error.message}`);
|
53 | }
|
54 | };
|
55 |
|
56 | module.exports = search;
|