-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_web_search.js
More file actions
52 lines (40 loc) · 1.5 KB
/
Copy pathsimple_web_search.js
File metadata and controls
52 lines (40 loc) · 1.5 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
const axios = require('axios');
const cheerio = require('cheerio');
async function performSearch(query, limit = 3) {
try {
const url = `https://www.google.com/search?q=${encodeURIComponent(query)}&num=${limit}`;
const headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
};
const response = await axios.get(url, { headers });
const $ = cheerio.load(response.data);
const results = [];
$('div.g').each((i, element) => {
if (i >= limit) return false;
const titleElement = $(element).find('h3');
const linkElement = $(element).find('a');
const snippetElement = $(element).find('.VwiC3b');
if (titleElement.length && linkElement.length) {
const title = titleElement.text().trim();
const url = linkElement.attr('href');
const description = snippetElement.text().trim() || 'No description available';
if (url && url.startsWith('http')) {
results.push({ title, url, description });
}
}
});
return JSON.stringify(results);
} catch (error) {
console.error('Search error:', error.message);
return JSON.stringify({ error: error.message });
}
}
const query = process.argv[2];
const limit = process.argv[3] ? parseInt(process.argv[3]) : 3;
if (!query) {
console.error('Please provide a search query');
process.exit(1);
}
performSearch(query, limit).then(results => {
console.log(results);
});