Giuseppe
Giuseppe

Reputation: 63

Output Script Results To HTML and Format

I have created a small script as a first-time web scraping project with python. It scrapes two different local news websites for the daily forecast (text) and the allergy forecast (.jpg). Naturally, printing to the console is not ideal, nor is importing Image to open the image file separately. Ideally, I would be able to insert both the text and image src into the body of an HTML file and perhaps link a CSS file to make it look a little nicer. Is this possible? I'm hesitant to build a full blown webapp for such a simple script but am open to it if that's the ideal approach. I'm open to any approach that might be considered best practice in this case. Code listed below.

from bs4 import BeautifulSoup
import urllib.request

kxanUrl = 'https://www.kxan.com/weather/forecast/todays-forecast/'
kxanPage = requests.get(kxanUrl)
kvueUrl = 'https://www.kvue.com/allergy'
kvuePage = requests.get(kvueUrl)

soup = BeautifulSoup(kxanPage.content, 'html.parser')
weatherHtmlData = soup.find("div", {"class": "article-content rich-text"})
weatherText = weatherHtmlData.get_text()

allergyImage = urllib.request.urlretrieve("http://cdn.tegna-media.com/kvue/weather/allergy16x9.jpg", "allergy_forecast.jpg")

Upvotes: 0

Views: 87

Answers (1)

puppydog
puppydog

Reputation: 385

Yep! That would be a totally fine approach. Take for example the following template:

template = """<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1   {color: blue;}
p    {color: red;}
</style>
</head>
<body>

<h1>Forecast</h1>
<div>
    $FORECAST_INFORMATION
</div>
<img src=$PATH_TO_ALLERGY_INFORMATION></img>

</body>
</html>""" 

# Pseudocode for writing a string to a file
write(string=template, file="~/results.html")

You could .replace $FORECAST_INFORMATION with your scraped data, and do the same with the file path to your scraped allergy image: $PATH_TO_ALLERGY_INFORMATION.

The above html was taken from: https://www.w3schools.com/html/html_css.asp

Upvotes: 1

Related Questions