-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcssSelector.js
68 lines (55 loc) · 1.47 KB
/
cssSelector.js
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
const CLIApp = require("./CLIApp");
class MyCLIApp extends CLIApp {
constructor() {
super();
this.expectedArgs = ["URL", "SELECTOR1", "[SELECTOR2] [SELECTOR3] ..."];
}
parseArgs(args) {
// check that an arg is given
if (args.length < 2) {
throw new Error(`Min 2 args required`);
}
// check if help was requested
if (args[0] === "-h" || args[0] === "--help") {
throw new Error();
}
// set path argument
this.URL = args[0];
this.cssSelectors = args.slice(1);
}
async execute() {
await this.findBySelector(this.URL, this.cssSelectors);
}
async findBySelector(URL, cssSelectors) {
// fetch HTML
const htmlContent = await this.getHTML(URL);
// load and find elements by cssSelector
this.findSelector(htmlContent, cssSelectors);
}
async getHTML(URL) {
const axios = require("axios");
try {
const response = await axios.get(URL);
return response.data;
} catch (error) {
console.log(error);
}
}
findSelector(htmlContent, cssSelectors) {
const cheerio = require("cheerio");
try {
const $ = cheerio.load(htmlContent);
const results = $(cssSelectors.join(" "));
if (results.length > 0) {
console.log(results.text());
} else {
console.log("No results found");
}
} catch (error) {
console.log(error);
}
}
}
// Create an instance of your CLI app and run it
const myApp = new MyCLIApp();
myApp.run();