Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to check horoscope using Python?
Python can be used to create a horoscope checker by web scraping horoscope websites. This tutorial shows how to fetch daily horoscope predictions using BeautifulSoup and the requests library.
Installing Required Packages
First, install the required packages
pip install beautifulsoup4 requests
The output shows successful installation
Collecting beautifulsoup4 Downloading beautifulsoup4-4.12.2.tar.gz (520 kB) Successfully installed beautifulsoup4-4.12.2 requests-2.31.0
Basic Horoscope Checker
Here's a simple script to fetch horoscope predictions
import requests
from bs4 import BeautifulSoup
# Zodiac signs mapped to their numeric IDs
zodiac_signs = {
"Aries": 1, "Taurus": 2, "Gemini": 3, "Cancer": 4,
"Leo": 5, "Virgo": 6, "Libra": 7, "Scorpio": 8,
"Sagittarius": 9, "Capricorn": 10, "Aquarius": 11, "Pisces": 12
}
def get_horoscope(sign, day):
"""Fetch horoscope for given zodiac sign and day"""
if sign not in zodiac_signs:
return "Invalid zodiac sign"
sign_id = zodiac_signs[sign]
url = f"https://www.horoscope.com/us/horoscopes/general/horoscope-general-daily-{day}.aspx?sign={sign_id}"
try:
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
horoscope_div = soup.find("div", attrs={"class": "main-horoscope"})
if horoscope_div and horoscope_div.p:
return horoscope_div.p.text.strip()
else:
return "Horoscope not found"
except Exception as e:
return f"Error fetching horoscope: {e}"
# Example usage
sign = "Virgo"
day = "today"
result = get_horoscope(sign, day)
print(f"Horoscope for {sign} ({day}): {result}")
Interactive Horoscope Checker
This version allows user input for zodiac sign and day
import requests
from bs4 import BeautifulSoup
def interactive_horoscope():
zodiac_signs = {
"Aries": 1, "Taurus": 2, "Gemini": 3, "Cancer": 4,
"Leo": 5, "Virgo": 6, "Libra": 7, "Scorpio": 8,
"Sagittarius": 9, "Capricorn": 10, "Aquarius": 11, "Pisces": 12
}
print("Available zodiac signs:")
for sign in zodiac_signs.keys():
print(f"- {sign}")
sign = input("Enter your zodiac sign: ").title()
day = input("Enter day (today/tomorrow/yesterday): ").lower()
if sign not in zodiac_signs:
print("Invalid zodiac sign!")
return
if day not in ['today', 'tomorrow', 'yesterday']:
print("Invalid day! Please enter today, tomorrow, or yesterday.")
return
try:
sign_id = zodiac_signs[sign]
url = f"https://www.horoscope.com/us/horoscopes/general/horoscope-general-daily-{day}.aspx?sign={sign_id}"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
horoscope_div = soup.find("div", attrs={"class": "main-horoscope"})
if horoscope_div and horoscope_div.p:
print(f"\n? Horoscope for {sign} ({day}):")
print(horoscope_div.p.text.strip())
else:
print("Sorry, horoscope not available at the moment.")
except requests.RequestException:
print("Error: Unable to connect to horoscope website.")
except Exception as e:
print(f"An error occurred: {e}")
# Run the interactive horoscope checker
interactive_horoscope()
Enhanced Horoscope Class
A more organized approach using a class
import requests
from bs4 import BeautifulSoup
class HoroscopeChecker:
def __init__(self):
self.zodiac_signs = {
"Aries": 1, "Taurus": 2, "Gemini": 3, "Cancer": 4,
"Leo": 5, "Virgo": 6, "Libra": 7, "Scorpio": 8,
"Sagittarius": 9, "Capricorn": 10, "Aquarius": 11, "Pisces": 12
}
self.base_url = "https://www.horoscope.com/us/horoscopes/general/"
def get_horoscope(self, sign, day="today"):
"""Get horoscope for specified sign and day"""
sign = sign.title()
if sign not in self.zodiac_signs:
return {"error": "Invalid zodiac sign"}
sign_id = self.zodiac_signs[sign]
url = f"{self.base_url}horoscope-general-daily-{day}.aspx?sign={sign_id}"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
horoscope_div = soup.find("div", attrs={"class": "main-horoscope"})
if horoscope_div and horoscope_div.p:
return {
"sign": sign,
"day": day,
"horoscope": horoscope_div.p.text.strip()
}
else:
return {"error": "Horoscope content not found"}
except requests.RequestException as e:
return {"error": f"Network error: {e}"}
except Exception as e:
return {"error": f"Parsing error: {e}"}
def get_multiple_horoscopes(self, signs, day="today"):
"""Get horoscopes for multiple signs"""
results = {}
for sign in signs:
results[sign] = self.get_horoscope(sign, day)
return results
# Example usage
checker = HoroscopeChecker()
# Single horoscope
result = checker.get_horoscope("Leo", "today")
if "error" in result:
print(f"Error: {result['error']}")
else:
print(f"? {result['sign']} ({result['day']}):")
print(result['horoscope'])
# Multiple horoscopes
signs = ["Aries", "Gemini", "Virgo"]
results = checker.get_multiple_horoscopes(signs, "today")
for sign, data in results.items():
if "error" not in data:
print(f"\n? {sign}: {data['horoscope'][:100]}...")
Key Features
The horoscope checker includes these features
- Error Handling Manages network issues and invalid inputs
- Input Validation Checks zodiac signs and day parameters
- Flexible Design Supports different days (today/tomorrow/yesterday)
- Class Structure Organized code for reusability
Important Notes
When web scraping horoscope sites
- Websites may change their structure, breaking the scraper
- Always respect the website's robots.txt and terms of service
- Add proper error handling for network timeouts
- Consider using API services for production applications
Conclusion
Python's requests and BeautifulSoup libraries make it easy to create horoscope checkers by web scraping. Always include proper error handling and respect website policies when scraping content.
Advertisements
