proxima
proxima

Reputation: 313

Extract JavaScript String from HTML page with Java

I want to get the value of a particular Javascript variable hard-coded in a html page. Visit the test-case with the following instructions:

The above response comes from the script given below, which is present in all the Shopify stores.

<script>
//<![CDATA[
      var Shopify = Shopify || {};
      Shopify.shop = "headphone-zone.myshopify.com";
      Shopify.theme = {"name":"Retina","id":8528293,"theme_store_id":601,"role":"main"};

//]]>
</script>

How to write a java code to get the value of Shopify.theme.theme_store_id field and store it?

Upvotes: 0

Views: 625

Answers (1)

Eric Leibenguth
Eric Leibenguth

Reputation: 4277

  • Get the html page as a String (see this post)
  • Detect the "Shopify.theme" keyword with a regex:

.

String patternString = "Shopify.theme\\s*=\\s*.*theme_store_id\\"\\:(\\d+)";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);

String themeStoreId;
while (matcher.find()) {
    themeStoreId = matcher.group(1);
}

Upvotes: 2

Related Questions