35 lines
823 B
JavaScript
35 lines
823 B
JavaScript
|
const { JSDOM } = require('jsdom');
|
||
|
|
||
|
// Function to query elements from a webpage
|
||
|
async function queryElements(url, selector) {
|
||
|
try {
|
||
|
// Fetch webpage content
|
||
|
const response = await fetch(url);
|
||
|
const html = await response.text();
|
||
|
|
||
|
// Create a DOM using jsdom
|
||
|
const dom = new JSDOM(html);
|
||
|
const doc = dom.window.document;
|
||
|
|
||
|
// Query elements using the provided selector
|
||
|
const elements = doc.querySelectorAll(selector);
|
||
|
|
||
|
// Return array of matching elements
|
||
|
return Array.from(elements);
|
||
|
} catch (error) {
|
||
|
console.error('Error:', error);
|
||
|
return [];
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Example usage:
|
||
|
const url = 'http://example.com';
|
||
|
const selector = 'a';
|
||
|
queryElements(url, selector)
|
||
|
.then(elements => {
|
||
|
console.log(elements);
|
||
|
})
|
||
|
.catch(error => {
|
||
|
console.error('Error:', error);
|
||
|
});
|