简体   繁体   中英

Scrape webpage using jQuery and get JSON object

There is a page (from the same domain) that I'm trying to scrape to only get a JSON which is inside <script> tag with a specific id

<div id="someID">
    <script type="text/json" id="scriptID">
      {
        "some more here": "and there",
        "there are many more": "and the structure is various"
      }
    </script>
  <script>
    console.log("just another script which can be with or without id")
  </script>
</div>

I'm trying to use ajax call to get the page but couldn't query in to that specific tag with that ID yet.

 $.ajax({
   url: "/someurlhere.com/htmlpage.html",
   dataType: 'html',
   success: function (data) {
     console.log($(data).find("script").attr("id", "scriptID"));
   }
 });

When I log that the output when I do:

var newData = $(data).find("script").attr("id", "ceci-definition").text();
console.log(newData);

I'm seeing the content of the second script instead

    console.log("just another script which can be with or without id")

Your use of find and attr aren't correct.

What you're doing is finding a script and setting its ID to scriptID .

Try this:

console.log($(data).find("script#scriptID").contents());

Basic example: http://jsfiddle.net/FbfE2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM