-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
161 lines (147 loc) · 3.63 KB
/
index.js
File metadata and controls
161 lines (147 loc) · 3.63 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
#!/usr/bin/env node
const axios = require('axios');
const cheerio = require('cheerio');
const parseMagnet = require('parse-magnet-uri').parseMagnet;
const { program, Option } = require('commander');
const pkg = require('./package.json');
// CLI options
program
.requiredOption('-u, --url <url>', 'The URL to scrape (required)')
.option('-s, --selector <selector>', 'CSS selector to find', 'a')
.addOption(
new Option(
'-c, --content <type>',
'Process each element as this type of content',
)
.choices([
'hash',
'html',
'image',
'json',
'link',
'object',
'text',
])
.default('link'),
)
.addOption(
new Option('-o, --output <format>', 'Output format')
.choices(['html', 'json', 'object', 'text'])
.default('text'),
)
.version(pkg.version);
program.addHelpText(
'after',
`
Examples:
Find all links and return their href
$ sss -u http://localhost:8080/test.html -s a -c link
Find all links and return their text
$ sss -u http://localhost:8080/test.html -s a -c text
Find all images and return their src
$ sss -u http://localhost:8080/test.html -s img -c image
Find all magnet links and return their infohash
$ sss -u http://localhost:8080/test.html -s a[href^=magnet] -c hash
`,
);
program.parse();
const options = program.opts();
/**
* Parses the HTML content based on the specified format.
* @param {string} body - The HTML content to parse.
* @returns {Array} - An array containing the parsed data.
*/
async function parse(body) {
const $ = cheerio.load(body);
const $content = $(options.selector);
if (!$content.length) {
throw new Error(
`Could not find any elements matching ${options.selector}`,
);
}
let result;
switch (options.content) {
case 'hash':
result = $content
.map((i, elem) => {
const magnet = parseMagnet(elem.attribs.href);
return magnet.infoHash;
})
.get();
break;
case 'html':
result = $content.map((i, elem) => $(elem).html()).get();
break;
case 'image':
result = $content.map((i, elem) => elem.attribs.src).get();
break;
case 'json':
result = $content.map((i, elem) => $(elem).text().trim()).get();
break;
case 'link':
result = $content.map((i, elem) => elem.attribs.href).get();
break;
case 'object':
result = $content;
break;
case 'text':
result = $content.map((i, elem) => $(elem).text()).get();
break;
default:
throw new Error('Invalid format option');
}
return result;
}
/**
* Outputs the parsed data based on the specified format.
* @param {Array} result - The parsed data to output.
*/
async function output(result) {
switch (options.output) {
case 'json':
console.log(JSON.stringify(result));
break;
case 'html':
case 'text':
console.log(result.join('\n'));
break;
case 'object':
console.log(result);
break;
default:
throw new Error('Invalid format option');
}
}
/**
* Scrapes the specified URL and outputs the data.
* @param {String} url - The URL to fetch.
*/
async function scrape(url) {
try {
const response = await axios.get(url, { timeout: 10000 });
if (response.status !== 200) {
throw new Error(`Unexpected status code: ${response.status}`);
}
return response.data;
} catch (error) {
if (error.response) {
throw new Error(
`Server responded with status code ${error.response.status}`,
);
}
if (error.request) {
throw new Error(`Request failed: ${error.message}`);
}
throw new Error(`An unexpected error occurred: ${error.message}`);
}
}
async function go() {
return scrape(options.url)
.then(parse)
.then(output)
.catch((error) => {
console.log(error.message);
process.exit(1);
});
}
go();