0

Much like this post here:(Google Sheet use Importxml error could not fetch url), I want to import a number from this website: (https://tarkov-market.com/item/Pack_of_sugar). Someone replied with a google apps script which takes the price and works wonderfully, their script was as follows:

function sampleFormula() {
  const url = "https://tarkov-market.com/item/Pack_of_sugar";
  const html = UrlFetchApp.fetch(url).getContentText();
  return html.match(/price:(.+?)<\/title>/)[1].trim();
}

However, I want to take the average price over the last 24 hours which is another number on the same page. I'm unfamiliar with coding but I'd like to know how to read the html.match part of this script and how to rewrite it to target a different number using information gained from "inspect element" I've tried rewriting the last line as:

return html.match(/Average price:(.+?)<\/title>/)[1].trim();
return html.match(/average:(.+?)<\/title>/)[1].trim();
return html.match(/"Average price":(.+?)<\/title>/)[1].trim();

But all return the error: "TypeError: Cannot read property '1' of null (line 4)."

If someone could post a corrected script or tell me where to learn about using html.match and inspecting elements, I would greatly appreciate it, thank you!

p.s. I apologize if this post isn't tagged appropriately.

Marios
  • 26,333
  • 8
  • 32
  • 52
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match – Cooper Jan 18 '21 at 22:32
  • [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Marios Jan 19 '21 at 15:58

1 Answers1

0

Try this:

function sampleFormula() {
  const url = "https://tarkov-market.com/item/Pack_of_sugar";
  const html = UrlFetchApp.fetch(url).getContentText();
  return html.match(/price(.*)<\/span>/)[1].split(">")[1]
}

or:

function sampleFormula() {
  const url = "https://tarkov-market.com/item/Pack_of_sugar";
  const html = UrlFetchApp.fetch(url).getContentText();
  return html.match(/price(.*)>(.*)<\/span>/)[2];
}

enter image description here

Marios
  • 26,333
  • 8
  • 32
  • 52
  • `text(.*)` means everything after text. For example `/price(.*)<\/span>/` means get everything between `price` and ``. – Marios Jan 18 '21 at 23:15
  • any character, possibly including newline but not always. I only add this because I've noticed recently that people put newlines in email html to make it difficult for spam software to capture their urls. – Cooper Jan 18 '21 at 23:48