首页 > 解决方案 > 从 index.html 请求 JSON - 这是从 url 获取数据的最佳方式

问题描述

我正在尝试为 HTML 页面做一个小搜索引擎。我正在使用一个输入框(自动完成),它必须给我所有的结果。基本上我正在使用这个查询:https://query2.finance.yahoo.com/v1/finance/search?q=tesla,我想在我输入内容后立即生成一个包含所有结果的 div。正如雅虎财经搜索所做的那样。我正在尝试使用 Cheerio,但我无法同时读取所有数据,但当时只能读取一个。这可能是解决这个问题的好代码。还有哪个是最好的方法,使用cheerio,还是我可以使用我过去用于Dash的python代码?

这里是新代码:

const axios = require("axios");
const cheerio = require("cheerio");
//performing a GET request
axios
  .get("https://query2.finance.yahoo.com/v1/finance/search?q=apple")
  .then((response) => {
    //handling the success
    const html = response.data;

    //loading response data into a Cheerio instance
    const $ = cheerio.load(html);

    var exchange = html.quotes[1].exchange;
    console.log(exchange);
  })
  //handling error
  .catch((error) => {
    console.log(error);
  });

我的旧 python 代码:(我想我不能再使用它了)

@app.callback(Output("output_ricerca", "children"),
              [Input("input", "value")])
def update_output(value):
        if str(value) == 'None':
            raise dash.exceptions.PreventUpdate
        apiurl = "https://query1.finance.yahoo.com/v1/finance/search?q="+ str(value)
        r = requests.get(apiurl)
        data = r.json()
        #print('value:')
        #print(apiurl)
        if apiurl != 'https://query1.finance.yahoo.com/v1/finance/search?q=':
            #print('vuoto')
            #print(data['quotes'])
            if data['quotes']:
              exchange = data["quotes"][0]['exchange']
              print(exchange)
              table_rows = [html.Tr([dcc.Link(href=z.get('symbol'),children=[z.get('symbol')]),html.Td(z.get('longname')),html.Td(z.get('quoteType')+'-'+z.get('exchange'))]) for z in data['quotes']]
            #rows_longname = [html.Tr([html.Td(z.get('longname'))]) for z in data['quotes']]
              output_table = html.Div(
               html.Table([
                  html.Th(scope="row",
                         children=[
                  html.Td('Symbols'),
                  ])
                  ]+table_rows),
                    style={
                    'position': 'fixed',
                    'z-index': 2147483647,
                    'top': '70px',
                    'left': '1150px',
                    'margin': 0,
                    'padding': 0,
                    'margin-bottom': '0px',
                    'display': 'inline',
                #'width': '100px',
                #'height':'100px'
                     })
            return output_table

标签: javascriptpythonjsonajaxcheerio

解决方案


推荐阅读