Tips for refining search outcomes from web scraping with Google App Script

My objective is to scrape data from the website :

I am specifically interested in extracting the SP500 PE number, which currently stands at 39.57 (at the time of writing). I require this number to be formatted as 39,57, rather than 39.57.

This is my current code:

function webScraper() {

var webURL = "https://www.multpl.com/s-p-500-pe-ratio";

var response = UrlFetchApp.fetch(webURL);

var $ = Cheerio.load(response.getContentText()); 

var itemsOfInterest = $('.info-left').first().text().trim();


Logger.log(itemsOfInterest)

return itemsOfInterest

}

The challenge: While my code successfully retrieves the information, it provides more details than needed. I need to refine the data and convert 39.57 to 39,57.

Here is the full set of information returned by the code:

Current S&P 500 PE Ratio: 39.57

+0.15 (0.39%)

4:00 PM EST, Fri Feb 5

Mean: 15.88

Median: 14.84

Min: 5.31

(Dec 1917)

Max: 123.73 (May 2009)

Price to earnings ratio, based on trailing twelve month “as reported” earnings.
Current PE is estimated from latest reported earnings and current market price.

Source: Robert Shiller and his book Irrational Exuberance for historic S&P 500 PE Ratio.

See also

Shiller PE Ratio

S&P 500 Price to Book Value

S&P 500 Price to Sales Ratio

S&P 500 Earnings Yield

S&P 500 Earnings

Inflation Adjusted S&P 500

Answer №1

It is my understanding that your objective is as follows.

  • You are looking to extract the value of 39.57 from the URL
    https://www.multpl.com/s-p-500-pe-ratio
    and convert it to 39,57.
  • You aim to accomplish this task using Google Apps Script.

Key Points for Modification:

  • Upon examining the HTML content of the URL, I noticed that the number 39.57 is present in a JSON object. It appears that by utilizing this information, you can easily retrieve the desired value.

In this response, I suggest a workaround which involves retrieving the value from the JSON object embedded within the HTML data. By implementing the following modifications into your script, the process will look like this:

Revised Script:

function webDataExtractor() {
  var websiteURL = "https://www.multpl.com/s-p-500-pe-ratio";
  var results = UrlFetchApp.fetch(websiteURL);
  var content = results.getContentText().match(/var d =([\s\S\w]+?);/);
  if (content && content.length > 0) {
    var objData = JSON.parse(content[1].trim());
    var output = objData.endLabel[0].replace(".", ",");  
    console.log(output) 
    return output;
  }
  return "No value found.";
}

Note:

  • This revised script specifically caters to the URL
    https://www.multpl.com/s-p-500-pe-ratio
    . Using it with other URLs may not yield the same results. Please take note of this distinction.

Resources:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AJAX: The form submission without refreshing the page only functions for the first attempt

My current issue involves using AJAX to submit a form without refreshing the page. The problem arises when I try to submit the form more than once, as the on('submit') function stops working after the initial submission. This defeats the purpose ...

Error message in Material-UI TextField not displaying when state is updated using Object.assign technique

Currently, I am facing an issue with validating a login form and displaying errors dynamically. These errors are passed as props from the child component. The problem arises when I set the errors object using Object.assign - the errorText does not show up ...

React: The new Date() function displays the date based on the client's machine, not the server

My react application is hosted on a server with a different locale, and I am utilizing new Date(). However, when I access the app from my client machine, it displays the date based on the client's locale rather than the server's. Why is this hap ...

Tips for retrieving the MenuItem name upon click event using Menu and MenuItem components in Material UI React

Utilizing MaterialUI's Menu and MenuItem components in a React project, I am looking to display the name of the menu item upon clicking on it. Upon inspecting event.currentTarget in console.log, it returns the entire list item: ListItem Image attache ...

The <SelectField> component in material-ui is not displaying items properly in ReactJS

I am facing an issue with Material-UI where the items are not showing up. I am trying to display categories of products in a SelectField but it doesn't seem to be working. When I click on the SelectField, no items are displayed. Below is the code for ...

I am receiving an undefined value when using document.getElementsByClassName

<canvas id="can" height="500px" width="1200px"></canvas> <div class="name"> <h1>LEONARDO</h1> </div> <script> var name=['WATSON','LEONARDO',"SMITH","EMILY"] var counter=0 var dat ...

Can we find a different way to address this issue with a "functional programming" mindset that doesn't involve utilizing the `forEach` method?

There has been a discussion about whether or not we still need to use forEach in JavaScript due to the availability of new language features. Some have suggested that this shift is an indirect push towards functional programming. I recently came across an ...

Attempting to locate the following div element using a particular class name, however, I consistently retrieve the final one

I have a magician and I'm attempting to design a progress bar. The current step that the user is on should be purple and should advance as the user moves through the form. However, when trying to proceed to the next step, the progress bar incorrectly ...

Oops! The module "rxjs/Subject" seems to be missing the exported member "Subject"

Here is the code I'm working with: import { Subject } from 'rxjs/Subject'; Upon importing this, an error occurs: rxjs/Subject" has no exported member 'Subject'. I am unable to fix this issue. Does anyone have a solution? ...

jquery autocomplete utilizing an external json data feed

I am facing an issue with my autocomplete function that was initially working with a local json source. I have decided to move it to an external json file, as my current code is lengthy (16k lines). However, I am struggling to make it work with the externa ...

Divide a collection of objects into groups based on 2-hour time spans

I have an array of objects that I need to split into chunks of 2 hours each, starting on the hour (e.g. 10.00 - 12.00, 12.00 - 14.00, etc). Here is my current solution, but I feel like it may not be the most efficient: Please consider the day variable, w ...

CSS responsive grid - adding a horizontal separator between rows

I currently have a responsive layout featuring a grid of content blocks. For desktop view, each row consists of 4 blocks. When viewed on a tablet, each row displays 3 blocks. On mobile devices, each row showcases 2 blocks only. I am looking to add a ho ...

Troubleshooting base href issues in AngularJS routing

For a demonstration, I decided to try out this plunker from a tutorial that showcases tab routing across different pages. After downloading the entire zip file and running it as is (e.g. with all files in the same directory and utilizing CDN links), I enco ...

A guide on how to implement the closing functionality of a CSS menu when clicking outside the menu using

I have a drop-down navigation menu implemented on a website using CSS. The sub-menus appear when hovering over specific items. While this functionality works well on desktop, I am encountering an issue on touchscreens. When clicking outside the menu area, ...

How can Typescript be leveraged to enforce a generic constraint on an interface?

I have defined 2 interface declarations : interface IStore { } interface AnotherInterface { a: number; } Also, there are 2 classes which implement each interface: class StoreImplementation implements IStore { } class AnotherImplementation implement ...

Grant the "User" the ability to modify both images and prices

I'm currently working on an art website for a relative and I am looking to provide them with the ability to log in and easily update the images of their paintings as well as adjust the pricing. Is it possible to enable this functionality? My assumptio ...

Determining the ultimate height of an element as it transitions in size using CSS

In situations where a CSS transition is ongoing, jQuery will return the current height of an element when its dimensions are requested. However, this may not always be desired. There are many cases where it's necessary to retrieve the final dimensions ...

Is it possible for a form to direct submissions to various pages depending on the value of certain fields

I need to set up a text field and submit button that will redirect users based on their input: index.html: If the user inputs "123" in the text box and clicks submit, they should be redirected to john.html page. AND If the user inputs "456" and clicks s ...

What is the best way to generate a dynamically interpolated string in JavaScript?

I'm currently developing a reusable UI component and am exploring options to allow the user of this component to provide their own template for a specific section within it. Utilizing TypeScript, I have been experimenting with string interpolation as ...

What are the best practices for utilizing AngularJS's $sanitize service?

Recently, I stumbled upon a tutorial discussing authentication in AngularJS. The tutorial showcased an AuthenticationService that was structured similarly to this: angular.module("auth").factory("AuthenticationService", function ($http, $sanitize) { ...