In this article, we are going to create a web app to get gaily News Using PyWebio
As we all download an app for receiving daily news but as a python lovers we try to do all these things via a python script. So here is a python script that notifies the daily news. In this script, we will create a web app using pywebio which shows all the top headlines as a pop-up window according to the name of country and category of news entered and selected by the user. Here we will extract an API key from the website so that we can extract the latest news and display them in a loop after a particular interval of time as a pop-up window.
Module Required:
- pycountry: pycountry provides the ISO databases for the standards.
pip install pycountry
- pywebio: PyWebIO contains functions for getting user input and output on the browser, turning the browser into a “rich text terminal”, and can be used to build simple web applications or browser-based GUI applications. With this module, anyone can produce a web application without any prior knowledge or overhead of HTML and JS.
pip install pywebio
- newsapi-python: Use the unofficial Python client library to integrate News API into your Python application without having to make HTTP requests directly.
pip install newsapi-python
Stepwise implementation:
Step 1: Firstly get your API key from newsapi and then import the following modules.
Python3
from newsapi import NewsApiClient import time import pycountry from pywebio. input import * from pywebio.output import * from pywebio.session import * |
Step 2: Load an API key(that you have extracted from the website) in a variable and take the name of the country as an input from the user.
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) |
Step 3: Now, this function will check that the country name i.e given by the user is valid or not. It checks by storing ISO codes of all the countries in a country dictionary and then if the entered country is not there in the dictionary then it returns an error message.
- Store input country in a variable.
- Create a dictionary and store all the countries in that along with their ISO codes.
- Now if the country name entered by the user is present there in the dictionary then move ahead else return an error message for the invalid country name.
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 |
Step 4: Here we get the choice of the user and save the data according to that in variables to display them further.
- Create a list of choice boxes using the radio function so that the user can select the category from which he/she wants to get the news.
- Then use the get_top_headlines function and pass category to it to store all the top latest news in a variable.
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' ] |
Step 5: Now we will print top headlines of news and their content in a loop as a pop-up window after a particular interval of time(you can set that as per your choice in the code below).
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( "<h4>" f "{articles['title'][:-b-2]}." "</h4>" ), put_buttons([ 'Close' ], onclick = lambda _: close_popup())], implicit_close = True ) time.sleep( 3 ) else : popup(f "{articles['title'][-b+1:]} News" , [put_html( "<h4>" f "{articles['title'][:-b-2]}." "</h4>" ), put_buttons([ 'Close' ], onclick = lambda _: close_popup())], implicit_close = True ) time.sleep( 3 ) |
Below is the full implementation:
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( "<p align=" "center" ">\ <img src = ""https: / / media0.giphy.com / media / kUTME7ABmhYg5J3psM / 200.webp ?\ cid = ecf05e47som5hu3l2owou9vmn20hue70j113dgls1ghb1909&rid = 200.webp &ct = g""\ width = " "120px" ">< / p> ") time.sleep( 3 ) clear() logo() # this will display the image of newspaper to create # an attractive interface. def logo(): put_html( "<p align=" "left" "><h4>\ " width=" "28px" ">NEWS< / h4>< / p> ") # 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( "<h4>" f "{articles['title'][:-b-2]}." "</h4>" ), put_buttons([ 'Close' ], onclick = lambda _: close_popup())], implicit_close = True ) time.sleep( 3 ) else : popup(f "{articles['title'][-b+1:]} News" , [put_html( "<h4>" f "{articles['title'][:-b-2]}." "</h4>" ), 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() |
Output: