import os
import requests
from bs4 import BeautifulSoup
from PIL import Image
from io import BytesIO

# Blog Post Creator Class
class BlogPostCreator:
def __init__(self, title, keywords, content_sections, output_dir=”blog_posts”):
self.title = title
self.keywords = keywords
self.content_sections = content_sections
self.output_dir = output_dir
self.api_key = “39172116-105870e030c80e0de044e71c1”
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)

def fetch_image(self, query):
“””Fetch an image from the Pixabay API.”””
print(f”Fetching image for: {query}”)
try:
url = f”https://pixabay.com/api/?key={self.api_key}&q={query}&image_type=photo”
response = requests.get(url)
data = response.json()
if data[‘hits’]:
image_url = data[‘hits’][0][‘webformatURL’]
image_response = requests.get(image_url)
img = Image.open(BytesIO(image_response.content))
return img
else:
print(“No image found for query.”)
return None
except Exception as e:
print(f”Error fetching image: {e}”)
return None

def insert_external_link(self, keyword):
“””Fetch a relevant external link using a search engine.”””
print(f”Fetching external link for: {keyword}”)
try:
search_url = f”https://www.google.com/search?q={keyword}”
headers = {“User-Agent”: “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36”}
response = requests.get(search_url, headers=headers)
soup = BeautifulSoup(response.text, ‘html.parser’)
link = soup.find(‘a’, href=True)
if link:
return link[‘href’]
else:
print(“No relevant link found.”)
return “#”
except Exception as e:
print(f”Error fetching link: {e}”)
return “#”

def generate_blog_post(self):
“””Generate the blog post and save as an HTML file.”””
print(“Generating blog post…”)
try:
post_content = f”{self.title}
post_content += f”

{self.title}

for section_title, section_text in self.content_sections.items():
post_content += f”

{section_title}

{section_text}

# Add an image if relevant
image = self.fetch_image(section_title)
if image:
image_path = os.path.join(self.output_dir, f”{section_title.replace(‘ ‘, ‘_’)}.jpg”)
image.save(image_path)
post_content += f’{section_title}

# Add an external link if relevant
link = self.insert_external_link(section_title)
if link:
post_content += f’

Read more: {link}

post_content += ““

# Save as an HTML file
output_file = os.path.join(self.output_dir, f”{self.title.replace(‘ ‘, ‘_’)}.html”)
with open(output_file, “w”, encoding=”utf-8″) as f:
f.write(post_content)

print(f”Blog post saved as {output_file}”)

except Exception as e:
print(f”Error generating blog post: {e}”)

# Example Usage
title = “The Importance of Sustainable Living”
keywords = [“sustainability”, “eco-friendly”, “green energy”]
content_sections = {
“Introduction”: “Sustainable living is about reducing our environmental impact.”,
“Why It Matters”: “The planet faces significant challenges such as climate change.”,
“Simple Steps to Start”: “Adopt habits like recycling and conserving energy.”,
}

blog_creator = BlogPostCreator(title, keywords, content_sections)
blog_creator.generate_blog_post()

Sign In

Register

Reset Password

Please enter your username or email address, you will receive a link to create a new password via email.