【问题标题】:How to scrape a JSON page with JavaScript and collect data如何使用 JavaScript 抓取 JSON 页面并收集数据
【发布时间】:2018-03-28 16:50:09
【问题描述】:

我想抓取https://api.coindesk.com/v1/bpi/currentprice/BTC.json/ 并收集比特币的价格,并将其保存到一个变量中。到目前为止,这是我的 js/jQuery 代码

$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('https://api.coindesk.com/v1/bpi/currentprice/BTC.json/') + '&callback=?', function(data){
    console.log(data.contents);
    var za = $((data.contents).find("rate_float").text();
    alert(za)
}));

我不断收到错误:

Uncaught SyntaxError: missing ) 在参数列表之后 它指向行:

var za = $((data.contents).find("rate_float").text();

不知道出了什么问题。我一遍又一遍地检查它,但所有括号都关闭了。任何帮助表示赞赏。谢谢

【问题讨论】:

  • $((中删除一个括号
  • 你记错括号了。
  • $(data.contents).find("rate_float").text() <- 我不知道你到底想做什么。
  • $((data.contents).find("rate_float").text(); 有一个额外的括号。
  • 好的。我已经卸下了支架。你知道我可以用什么来代替“rate_float”来捕捉比特币价格吗?

标签: javascript jquery json web-scraping


【解决方案1】:

返回值为 JSON 字符串。您需要解析才能将该字符串转换为 js 对象,例如:

{
     "time": {
         "updated": "Mar 28, 2018 16:58:00 UTC",
         "updatedISO": "2018-03-28T16:58:00+00:00",
         "updateduk": "Mar 28, 2018 at 17:58 BST"
     },
     "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
     "bpi": {
         "USD": {
             "code": "USD",
             "rate": "7,882.7938",
             "description": "United States Dollar",
             "rate_float": 7882.7938
         },
         "BTC": {
             "code": "BTC",
             "rate": "1.0000",
             "description": "Bitcoin",
             "rate_float": 1
         }
     }
 }

为了得到美元 rate_float,你可以这样写:

var za = JSON.parse(data.contents).bpi.USD.rate_float;

完整代码:

$.getJSON('http://www.whateverorigin.org/get?url=' +
        encodeURIComponent('https://api.coindesk.com/v1/bpi/currentprice/BTC.json') + '&callback=?', function (data) {
    console.log(data.contents);
    var za = JSON.parse(data.contents).bpi.USD.rate_float;
    alert(za)
});

【讨论】:

    【解决方案2】:

    工作演示

    // handles the click event, sends the query
    function getSuccessOutput() {
        $.ajax({
            url:'https://api.coindesk.com/v1/bpi/currentprice/BTC.json',
            complete: function (response) {
                $('#output').html(JSON.parse(response.responseText).bpi.USD.rate_float);
            },
            error: function () {
                $('#output').html('there was an error!');
            },
        });
        return false;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#" onclick="return getSuccessOutput();"> Get USD price </a>
    <hr>
    <div id="output">Click on link to get the output</div>

    【讨论】:

      猜你喜欢
      • 2021-07-12
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      相关资源
      最近更新 更多