如何使用dash/python在html列表中创建动态搜索结果,而不使用submit botton

2024-09-27 09:36:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个动态搜索框,允许做研究和自动完成。 我希望当我在搜索框中键入内容而不按下按钮时,我会有一个带有结果的HTML.Div。 它在雅虎财经搜索框中的具体工作方式。 我正在尝试,但没有好的结果,首先它非常慢,当我点击搜索框外的指针时它就工作了,所以它不是活动的,第二,只返回最后一个结果。 相反,我需要所有结果在HTML div中弹出,而不是在dropbox中。 我试着这样做:

 app.layout = html.Div([
        dcc.Input(id='username', value='', type='text'),
        #html.Button(id='submit-button', type='submit', children='Submit'),
        html.Div(id='output_div')
    ])

    @app.callback(Output('output_div', 'children'),
                  [Input('username', 'value')],
                  )
    def update_output(input_value):
            print('iniziale:')
            print(input_value)
            list_a = [input_value]
            list_b = [" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "l", "m", "n", "o", "p", "q", "r", "s", "t", "v", "z",
            "ü", "ä", "ö", "y", "w", "x"]
            list_c = [f"{i} {j}" for i in list_a for j in list_b]
            for x in list_c:
                apiurl = "https://query1.finance.yahoo.com/v1/finance/search?q="+x+"&quotesCount=6&quotesQueryId=tss_match_phrase_query&multiQuoteQueryId=multi_quote_single_token_query&enableNavLinks=true&enableEnhancedTrivialQuery=true"
                r = requests.get(apiurl)
                data = r.json()
                if data['quotes']:
                    longname = data["quotes"][0]["longname"],
                    print(longname)
            return longname
        #[html.Div(children=f'Div #{i}') for i in range (len(longname))]

如何做到这一点?我试了又试,但没有结果。要帮忙吗

好吧,假设这是我的json数据:

{"explains":[],"count":15,"quotes":[{"exchange":"NMS","shortname":"Tesla, Inc.","quoteType":"EQUITY","symbol":"TSLA","index":"quotes","score":596601.0,"typeDisp":"Equity","longname":"Tesla, Inc.","isYahooFinance":true},{"exchange":"MEX","shortname":"TESLA INC","quoteType":"EQUITY","symbol":"TSLA.MX","index":"quotes","score":20404.0,"typeDisp":"Equity","longname":"Tesla, Inc.","isYahooFinance":true},{"exchange":"GER","shortname":"TESLA INC. DL -,001","quoteType":"EQUITY","symbol":"TL0.DE","index":"quotes","score":20348.0,"typeDisp":"Equity","longname":"Tesla, Inc.","isYahooFinance":true},{"exchange":"FRA","shortname":"TESLA INC. DL -,001","quoteType":"EQUITY","symbol":"TL0.F","index":"quotes","score":20183.0,"typeDisp":"Equity","longname":"Tesla, Inc.","isYahooFinance":true},{"exchange":"BUE","shortname":"TESLA INC","quoteType":"EQUITY","symbol":"TSLA.BA","index":"quotes","score":20124.0,"typeDisp":"Equity","longname":"Tesla, Inc.","isYahooFinance":true},{"exchange":"PNK","shortname":"TESLA EXPLORATION LTD","quoteType":"EQUITY","symbol":"TXLZF","index":"quotes","score":20059.0,"typeDisp":"Equity","longname":"Tesla Exploration Ltd.","isYahooFinance":true},{"exchange":"LSE","shortname":"GRANITESHARES FINANCIAL PLC GRA","quoteType":"EQUITY","symbol":"3STS.L","index":"quotes","score":20048.0,"typeDisp":"Equity","longname":"GraniteShares 3x Short Tesla Daily ETP","isYahooFinance":true}],"news":[{"uuid":"9caaa590-b553-3f46-a676-52d7a022efa0","title":"Dow Jones Futures: Stock Market Rally Flashes Mixed Signals; Why Apple, Nio, Zoom Video Are Important","publisher":"Investor's Business Daily","link":"https://finance.yahoo.com/m/9caaa590-b553-3f46-a676-52d7a022efa0/dow-jones-futures%3A-stock.html","providerPublishTime":1606680130,"type":"STORY"},{"uuid":"289ae8b8-6afe-3cf8-b184-077681ed3270","title":"ETFs for the Driverless Car Revolution","publisher":"Investopedia","link":"https://finance.yahoo.com/m/289ae8b8-6afe-3cf8-b184-077681ed3270/etfs-for-the-driverless-car.html","providerPublishTime":1606675634,"type":"STORY"},{"uuid":"bdaea0b0-a8c6-3fac-b597-f1d061f79cf8","title":"Tesla To Spend $6.4M On New Supercharger Factory In China","publisher":"Benzinga","link":"https://finance.yahoo.com/news/tesla-spend-6-4m-supercharger-172329678.html","providerPublishTime":1606670609,"type":"STORY"},{"uuid":"d8c6cf8f-cddf-3c88-93b5-5305f1b4ca48","title":"The Only Electric Car Stock Worth Buying","publisher":"Motley Fool","link":"https://finance.yahoo.com/m/d8c6cf8f-cddf-3c88-93b5-5305f1b4ca48/the-only-electric-car-stock.html","providerPublishTime":1606662000,"type":"STORY"},{"uuid":"b3419178-c811-378e-9106-a150c40ec31c","title":"Here's What All Investors Should Know About Shorting Stocks","publisher":"Motley Fool","link":"https://finance.yahoo.com/m/b3419178-c811-378e-9106-a150c40ec31c/here%27s-what-all-investors.html","providerPublishTime":1606651980,"type":"STORY"},{"uuid":"39fb680c-12ab-3ef0-a792-efc1d8fafb90","title":"The 3 Most Dangerous Investing Bubbles Waiting to Burst","publisher":"Motley Fool","link":"https://finance.yahoo.com/m/39fb680c-12ab-3ef0-a792-efc1d8fafb90/the-3-most-dangerous.html","providerPublishTime":1606649760,"type":"STORY"},{"uuid":"4d224e7e-59c9-37df-b841-9a47989fc6b6","title":"Top 11 Lithium and Battery Stocks to Buy Now","publisher":"Insider Monkey","link":"https://finance.yahoo.com/news/top-11-lithium-battery-stocks-031442126.html","providerPublishTime":1606619682,"type":"STORY"},{"uuid":"f4d2a6f4-d714-381d-97a9-0df84828885f","title":"Stock Market Today: Nasdaq Notches Another High as COVID's Spread Worsens","publisher":"Kiplinger","link":"https://finance.yahoo.com/news/stock-market-today-nasdaq-notches-182341710.html","providerPublishTime":1606610750,"type":"STORY"}],"nav":[],"lists":[],"researchReports":[],"totalTime":28,"timeTakenForQuotes":410,"timeTakenForNews":700,"timeTakenForAlgowatchlist":400,"timeTakenForPredefinedScreener":400,"timeTakenForCrunchbase":0,"timeTakenForNav":400,"timeTakenForResearchReports":0}

现在我使用一个输入框(搜索框)来获取这些结果/自动竞争建议。 如何创建一个搜索框,为我提供一个包含所有这些结果的HTML表


Tags: httpscomtrueuuidtitlehtmltypelink
2条回答

正确答案是:

table_rows = [html.Tr([html.Td(z.get('symbol')),html.Td(z.get('longname')),html.Td(z.get('quoteType')+'-'+z.get('exchange'))]) for z in data['quotes']]

我不确定这应该做什么:

list_a = [input_value]
list_b = [" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "l", "m", "n", "o", "p",     "q", "r", "s", "t", "v", "z",
          "ü", "ä", "ö", "y", "w", "x"]
list_c = [f"{i} {j}" for i in list_a for j in list_b]

但我不确定这是你想要的。当我输入文本“hello”时,list_c中的值是:

['hello  ', 'hello a', 'hello b', 'hello c', 'hello d', 'hello e', 'hello f', 'h
ello g', 'hello h', 'hello i', 'hello l', 'hello m', 'hello n', 'hello o', 'hell
o p', 'hello q', 'hello r', 'hello s', 'hello t', 'hello v', 'hello z', 'hello ü
', 'hello ä', 'hello ö', 'hello y', 'hello w', 'hello x']

那似乎没用

像您这样接受输入并直接输出到div没有什么错,但这并不是以一种快速的方式编写的。每次启动回调时,它都会执行大约20多次API请求。这需要一点时间。要使它真正快速,您最多需要在每次回调执行时执行1个API请求

您也没有longname的初始值,因此如果从未定义该变量,则回调可能最终返回None

how can I create a search box that gives me an HTML table with all these results?

您可以对结果进行循环,并以所需的格式将其放入表中。这是我创建的一个非常简单的表。当我使用您的样本数据作为DATA在本地运行它时,它工作了

def update_output(input_value):
    table_rows = [html.Tr([html.Td(x['longname'])]) for x in DATA['quotes']]
    output_table = html.Table([
        html.Th([
            html.Td('Longname'),
        ]),
        html.Tr([
            html.Td(input_value)
        ]),
    ] + table_rows)
    return output_table

相关问题 更多 >

    热门问题