I am in the process of learning Node JS and how to web scrape. I thought it would be a good approach to extract columns from a wikipedia page https://en.wikipedia.org/wiki/List_of_S%26P_500_companies
I've been learning about web scraping with Cheerio but am unsure how to code this in NodeJS. I've become familiar with html selectors to identify elements on a page but am not sure how to extract into a program. I plan on extracting this information into a list. I am hoping to extract the Symbol and Security columns on the table on the wiki page.
Below is the code I have compiled and the result I am getting. I have created a const based off a selector on the webpage. I believe it is supposed to return all the values in the column based off the selector.
var AWS = require("aws-sdk");
var AWS = require("aws-sdk/global");
AWS.config.apiVersions = {
dynamodb: '2012-08-10'
};
var dynamodb = new AWS.DynamoDB();
const cheerio = require('cheerio');
const axios = require('axios');
const express = require('express');
async function getStocks() {
try {
const url = ' https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
const { data } = await axios({
method: "GET",
url: url,
})
const $ = cheerio.load(data)
const elemSelector = '#constituents > tbody > tr:nth-child(1) > td'
$(elemSelector).each((parentIdx, parentElem) => {
console.log(parentIdx)
})
console.log($)
} catch (err) {
console.error(err)
}
}
getStocks()
Result
[Function: initialize] {
html: [Function: html],
xml: [Function: xml],
text: [Function: text],
parseHTML: [Function: parseHTML],
root: [Function: root],
contains: [Function: contains],
merge: [Function: merge],
load: [Function: load],
_root: Node {
type: 'root',
name: 'root',
parent: null,
prev: null,
next: null,
children: [ [Node], [Node] ],
'x-mode': 'no-quirks'
},
_options: { xml: false, decodeEntities: true },
fn: Cheerio { constructor: [Function: LoadedCheerio] }
}
[Finished in 2.384s]