【问题标题】:i want the code to wait for previous line to be done before continuing我希望代码在继续之前等待上一行完成
【发布时间】:2021-12-29 07:29:41
【问题描述】:

嗨,我正在使用 streamlit 从用户那里获取输入,并使用 GoogleNews 模块搜索与输入文本相关的新闻并将它们存储在变量“result_0”中。 但我希望在继续之前完成以下步骤

googlenews.search(inputt.iloc[0,0])
googlenews.get_news(inputt.iloc[0,0])
result_0 = googlenews.page_at(1)

但实际上发生的事情是系统直接进入下一行:

if len(result_0) == 0:

它总是正确的,因为结果没有机会从上一步加载新闻我尝试使用 time.sleep() 函数但我不确定这一步需要多长时间,因为新闻的数量取决于输入文本

【问题讨论】:

  • search()get_news() 是否异步?

标签: python streamlit google-news


【解决方案1】:

问题在于您如何使用GoogleNews 包。 这是使用GoogleNews在流式应用程序中按术语显示新闻的代码:

import streamlit as st
from GoogleNews import GoogleNews

# add app title
st.title('Google news')
st.markdown("""---""")

# get user input for seraching news
user_input = st.sidebar.text_input("Enter news term")

state = st.sidebar.button("Get News!")

if state:
    # get news
    googlenews = GoogleNews()
    googlenews.get_news(user_input)
    news = googlenews.results()
    if news:
        for i in news:            
            st.markdown(f"**{i['title']}**")
            st.write(f"Published Date - {i['date']}")
            st.markdown(f"[Article Link]({i['link']})")
            st.markdown("---")
            
    else:
        st.write("No news for this term")

这是输出:

另外我建议您改用GNews 包,因为它具有更好的功能。下面是使用 GNews 在流式应用中按术语显示新闻的代码:

import streamlit as st
from gnews import GNews

# add app title
st.title('Google news')
st.markdown("""---""")

# get user input for seraching news
user_input = st.sidebar.text_input("Enter news term")

state = st.sidebar.button("Get News!")

if state:
    # get news
    news = GNews().get_news(user_input)
    if news:
        for i in news:
            st.markdown(f"**{i['title']}**")
            st.write(f"Published Date - {i['published date']}")
            st.write(i["description"])
            st.markdown(f"[Article Link]({i['url']})")
            st.markdown("""---""")
    else:
        st.write("No news for this term")

这是输出:

【讨论】:

    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多