每日最新消息 webapp 在Python使用 PyWebio
在本文中,我们将创建一个 Web 应用程序来使用 PyWebio 获取欢快的新闻
因为我们都下载了一个应用程序来接收每日新闻,但作为一个Python爱好者,我们尝试通过Python脚本来完成所有这些事情。所以这里有一个通知每日新闻的Python脚本。在此脚本中,我们将使用 pywebio 创建一个 Web 应用程序,该应用程序根据用户输入和选择的国家/地区名称和新闻类别将所有头条新闻显示为弹出窗口。在这里,我们将从网站中提取一个 API 密钥,以便我们可以提取最新消息,并在特定时间间隔后将它们作为弹出窗口循环显示。
模块要求:
- pycountry: pycountry 提供标准的 ISO 数据库。
pip install pycountry
- pywebio: PyWebIO 包含在浏览器上获取用户输入和输出的功能,将浏览器变成“富文本终端”,可用于构建简单的 Web 应用程序或基于浏览器的 GUI 应用程序。有了这个模块,任何人都可以在没有 HTML 和 JS 的任何先验知识或开销的情况下生成 Web 应用程序。
pip install pywebio
- newsapi-python:使用非官方的Python客户端库将新闻 API 集成到您的Python应用程序中,而无需直接发出 HTTP 请求。
pip install newsapi-python
分步实施:
步骤 1:首先从newsapi获取您的 API 密钥,然后导入以下模块。
Python3
from newsapi import NewsApiClient
import time
import pycountry
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
Python3
# copy your api id from website
# and paste it here by replacing 'Your API Key'
newsapi = NewsApiClient(api_key='Your API Key')
# required = True ensures that input can't be empty
input_country = input("", placeholder = "Enter Country Name",
required = True, validate = Check)
Python3
def Check(input_countries):
input_countries = [input_countries.strip()]
countries = {}
for country in pycountry.countries:
countries[country.name] = country.alpha_2
codes = [countries.get(country.title(),
'NO')for country in input_countries]
if codes[0] == "NO":
return "Wrong Country Name: Country not found..."
return None
Python3
# create a choice box for
# selecting type of news one wants to see
option = radio("Which category are you interested in?",
options = ['Business', 'Entertainment',
'General', 'Health','Science',
'Technology'], required=True)
# extract dictionary of top
# headlines including articles etc.
top_headlines = newsapi.get_top_headlines(category = f'
{option.lower()}',
language='en',
country=f'
{codes[0].lower()}')
Headlines = top_headlines['articles']
Python3
for articles in Headlines:
b = articles['title'][::-1].index("-")
if "news" in (articles['title'][-b+1:]).lower():
popup(f"{articles['title'][-b+1:]}",
[put_html(""f"{articles['title'][:-b-2]}.""
"),
put_buttons(['Close'], onclick=lambda _: close_popup())],
implicit_close=True)
time.sleep(3)
else:
popup(f"{articles['title'][-b+1:]} News",
[put_html(""f"{articles['title'][:-b-2]}.""
"),
put_buttons(['Close'], onclick=lambda _: close_popup())],
implicit_close=True)
time.sleep(3)
Python3
from newsapi import NewsApiClient
import time
import pycountry
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
def Check(input_countries):
input_countries = [input_countries.strip()]
countries = {}
for country in pycountry.countries:
countries[country.name] = country.alpha_2
codes = [countries.get(country.title(), 'NO')
for country in input_countries]
if codes[0] == "NO":
return "Wrong Country Name: Country not found..."
return None
# this will display the loading gif to create an
# attractive interface.
def progress():
put_html("\
")
time.sleep(3)
clear()
logo()
# this will display the image of newspaper to create
# an attractive interface.
def logo():
put_html("\
NEWS
")
# this will display as a pop up in starting.
toast('LATEST NEWS NOTIFIER PRESENTED BY ADITYA',
position='center', color='#000000', duration=3,
onclick=clear)
time.sleep(3)
# this will run the below code until all
# the news headlines are displayed successfully one by one
while 1:
clear()
logo()
# paste your unique API id here
newsapi = NewsApiClient(api_key='d680fd29ce414518ad6c0585fb00143b')
# take name of country as an input from the user
input_country = input("", placeholder="Enter Country Name",
required=True, validate=Check)
progress()
input_countries = [f'{input_country.strip()}']
countries = {}
for country in pycountry.countries:
countries[country.name] = country.alpha_2
codes = [countries.get(country.title(),
'Unknown code')for country in input_countries]
option = radio("Which category are you interested in?",
options=['Business', 'Entertainment',
'General', 'Health', 'Science',
'Technology'],
required=True)
progress()
top_headlines = newsapi.get_top_headlines(category=f'{option.lower()}',
language='en',
country=f'{codes[0].lower()}')
Headlines = top_headlines['articles']
if Headlines:
for articles in Headlines:
b = articles['title'][::-1].index("-")
if "news" in (articles['title'][-b+1:]).lower():
popup(f"{articles['title'][-b+1:]}",
[put_html(""f"{articles['title'][:-b-2]}.""
"),
put_buttons(['Close'],
onclick=lambda _: close_popup())],
implicit_close=True)
time.sleep(3)
else:
popup(f"{articles['title'][-b+1:]} News",
[put_html(""f"{articles['title'][:-b-2]}.""
"),
put_buttons(['Close'],
onclick=lambda _: close_popup())],
implicit_close=True)
time.sleep(3)
else:
put_error(f"No articles found for {input_country},
Try for others...", closable=True)
time.sleep(3)
clear()
clear()
logo()
option = radio("Do you want to search again?",
options=['Yes', 'No'], required=True)
if option == 'Yes':
continue
else:
toast("Thanks For Visiting!")
exit()
第 2 步:在变量中加载 API 密钥(您从网站中提取的),并将国家/地区名称作为用户的输入。
蟒蛇3
# copy your api id from website
# and paste it here by replacing 'Your API Key'
newsapi = NewsApiClient(api_key='Your API Key')
# required = True ensures that input can't be empty
input_country = input("", placeholder = "Enter Country Name",
required = True, validate = Check)
第 3 步:现在,此函数将检查用户提供的国家/地区名称是否有效。它通过将所有国家/地区的ISO 代码存储在国家/地区词典中进行检查,然后如果输入的国家/地区不在词典中,则返回错误消息。
- 将输入国家/地区存储在变量中。
- 创建字典并将其中的所有国家/地区及其 ISO 代码存储起来。
- 现在,如果用户输入的国家/地区名称存在于字典中,则继续前进,否则返回无效国家/地区名称的错误消息。
蟒蛇3
def Check(input_countries):
input_countries = [input_countries.strip()]
countries = {}
for country in pycountry.countries:
countries[country.name] = country.alpha_2
codes = [countries.get(country.title(),
'NO')for country in input_countries]
if codes[0] == "NO":
return "Wrong Country Name: Country not found..."
return None
步骤4:这里我们得到用户的选择,并根据变量中的数据保存以进一步显示它们。
- 使用收音机函数创建一个选择框列表,以便用户可以选择他/她想要从中获取新闻的类别。
- 然后使用 get_top_headlines函数并将 category 传递给它以将所有最新的新闻存储在一个变量中。
蟒蛇3
# create a choice box for
# selecting type of news one wants to see
option = radio("Which category are you interested in?",
options = ['Business', 'Entertainment',
'General', 'Health','Science',
'Technology'], required=True)
# extract dictionary of top
# headlines including articles etc.
top_headlines = newsapi.get_top_headlines(category = f'
{option.lower()}',
language='en',
country=f'
{codes[0].lower()}')
Headlines = top_headlines['articles']
第 5 步:现在我们将在特定时间间隔后以弹出窗口的形式循环打印新闻的头条新闻及其内容(您可以在下面的代码中根据自己的选择进行设置)。
蟒蛇3
for articles in Headlines:
b = articles['title'][::-1].index("-")
if "news" in (articles['title'][-b+1:]).lower():
popup(f"{articles['title'][-b+1:]}",
[put_html(""f"{articles['title'][:-b-2]}.""
"),
put_buttons(['Close'], onclick=lambda _: close_popup())],
implicit_close=True)
time.sleep(3)
else:
popup(f"{articles['title'][-b+1:]} News",
[put_html(""f"{articles['title'][:-b-2]}.""
"),
put_buttons(['Close'], onclick=lambda _: close_popup())],
implicit_close=True)
time.sleep(3)
下面是完整的实现:
蟒蛇3
from newsapi import NewsApiClient
import time
import pycountry
from pywebio.input import *
from pywebio.output import *
from pywebio.session import *
def Check(input_countries):
input_countries = [input_countries.strip()]
countries = {}
for country in pycountry.countries:
countries[country.name] = country.alpha_2
codes = [countries.get(country.title(), 'NO')
for country in input_countries]
if codes[0] == "NO":
return "Wrong Country Name: Country not found..."
return None
# this will display the loading gif to create an
# attractive interface.
def progress():
put_html("\
")
time.sleep(3)
clear()
logo()
# this will display the image of newspaper to create
# an attractive interface.
def logo():
put_html("\
NEWS
")
# this will display as a pop up in starting.
toast('LATEST NEWS NOTIFIER PRESENTED BY ADITYA',
position='center', color='#000000', duration=3,
onclick=clear)
time.sleep(3)
# this will run the below code until all
# the news headlines are displayed successfully one by one
while 1:
clear()
logo()
# paste your unique API id here
newsapi = NewsApiClient(api_key='d680fd29ce414518ad6c0585fb00143b')
# take name of country as an input from the user
input_country = input("", placeholder="Enter Country Name",
required=True, validate=Check)
progress()
input_countries = [f'{input_country.strip()}']
countries = {}
for country in pycountry.countries:
countries[country.name] = country.alpha_2
codes = [countries.get(country.title(),
'Unknown code')for country in input_countries]
option = radio("Which category are you interested in?",
options=['Business', 'Entertainment',
'General', 'Health', 'Science',
'Technology'],
required=True)
progress()
top_headlines = newsapi.get_top_headlines(category=f'{option.lower()}',
language='en',
country=f'{codes[0].lower()}')
Headlines = top_headlines['articles']
if Headlines:
for articles in Headlines:
b = articles['title'][::-1].index("-")
if "news" in (articles['title'][-b+1:]).lower():
popup(f"{articles['title'][-b+1:]}",
[put_html(""f"{articles['title'][:-b-2]}.""
"),
put_buttons(['Close'],
onclick=lambda _: close_popup())],
implicit_close=True)
time.sleep(3)
else:
popup(f"{articles['title'][-b+1:]} News",
[put_html(""f"{articles['title'][:-b-2]}.""
"),
put_buttons(['Close'],
onclick=lambda _: close_popup())],
implicit_close=True)
time.sleep(3)
else:
put_error(f"No articles found for {input_country},
Try for others...", closable=True)
time.sleep(3)
clear()
clear()
logo()
option = radio("Do you want to search again?",
options=['Yes', 'No'], required=True)
if option == 'Yes':
continue
else:
toast("Thanks For Visiting!")
exit()
输出: