-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
176 lines (132 loc) · 4.75 KB
/
Copy pathmain.py
File metadata and controls
176 lines (132 loc) · 4.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""
Random Quotes Generator
Scrapes quotes from quotes.toscrape.com and saves to CSV
"""
import requests
from bs4 import BeautifulSoup
import csv
import random
def scrape_quotes(base_url="https://wisdomquotes.com/famous-quotes/"):
"""
Scrape all quotes from the website
Args:
base_url (str): Base URL of quotes website
Returns:
list: List of quote dictionaries
"""
quotes_list = []
url = base_url
page = 1
print("Scraping quotes...")
while True:
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Find all quote containers
quotes = soup.find_all('div', class_='quote')
if not quotes:
break
for quote in quotes:
# Extract quote text
text = quote.find('span', class_='text').text
# Extract author
author = quote.find('small', class_='author').text
# Extract tags
tags = [tag.text for tag in quote.find_all('a', class_='tag')]
quotes_list.append({
'quote': text,
'author': author,
'tags': ', '.join(tags)
})
print(f" Page {page}: {len(quotes)} quotes scraped")
page += 1
# Find next page
next_btn = soup.find('li', class_='next')
if not next_btn:
break
next_link = next_btn.find('a')['href']
url = base_url + next_link
except Exception as e:
print(f"Error scraping page {page}: {e}")
break
return quotes_list
def save_to_csv(quotes, filename="quotes.csv"):
"""
Save quotes to CSV file
Args:
quotes (list): List of quote dictionaries
filename (str): Output CSV filename
"""
try:
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
fieldnames = ['quote', 'author', 'tags']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(quotes)
print(f"\n✓ Quotes saved to: {filename}")
print(f" Total quotes: {len(quotes)}")
except Exception as e:
print(f"Error saving to CSV: {e}")
def display_random_quote(quotes):
"""
Display a random quote
Args:
quotes (list): List of quote dictionaries
"""
if not quotes:
print("No quotes available!")
return
quote = random.choice(quotes)
print("\n" + "="*70)
print(" RANDOM QUOTE")
print("="*70)
print(f"\n{quote['quote']}")
print(f"\n — {quote['author']}")
if quote['tags']:
print(f"\n Tags: {quote['tags']}")
print("="*70 + "\n")
def main():
"""Main function"""
print("\n" + "="*70)
print(" QUOTES SCRAPER & GENERATOR")
print("="*70 + "\n")
try:
print("Options:")
print(" 1. Scrape quotes and save to CSV")
print(" 2. Display random quote (from scraped data)")
print(" 3. Both")
choice = input("\nEnter choice (1-3): ").strip()
if choice in ['1', '3']:
quotes = scrape_quotes()
if quotes:
save_to_csv(quotes)
if choice == '3':
display_random_quote(quotes)
else:
print("No quotes scraped!")
elif choice == '2':
# Try to load from existing CSV
try:
quotes = []
with open('quotes.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
quotes = list(reader)
if quotes:
while True:
display_random_quote(quotes)
again = input("Show another quote? (y/n): ").strip().lower()
if again != 'y':
break
else:
print("No quotes found in CSV!")
except FileNotFoundError:
print("Error: quotes.csv not found! Please scrape quotes first (option 1).")
else:
print("Invalid choice!")
except KeyboardInterrupt:
print("\n\nProgram interrupted. Goodbye!")
except Exception as e:
print(f"\nError: {e}")
if __name__ == "__main__":
main()