-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
369 lines (324 loc) · 13.9 KB
/
app.py
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# import streamlit as st
# from bs4 import BeautifulSoup
# import requests
# def get_news_text(url):
# page = requests.get(url)
# soup = BeautifulSoup(page.text, 'lxml')
# news_paragraphs = soup.find_all('p')[:2]
# news_text = '\n'.join([p.text.strip() for p in reversed(news_paragraphs)])
# return news_text
# def scrape_and_summarize(category_url):
# news_data = []
# for page_num in range(1, 6):
# page_url = f"{category_url}/page-{page_num}"
# r = requests.get(page_url)
# soup = BeautifulSoup(r.text, 'lxml')
# for h2_tag in soup.find_all('h2'):
# headline = h2_tag.text.strip()
# link = h2_tag.a['href']
# news_text = get_news_text(link)
# news_data.append({"headline": headline, "news_text": news_text, "link": link})
# return news_data
# st.title("News Aggregator")
# categories = [
# "India",
# "Elections",
# "Latest",
# "Cities",
# "Education",
# "Trends",
# "Offbeat",
# "South"
# ]
# selected_category = st.selectbox("Select a category:", categories)
# category_urls = {
# "India": "https://www.ndtv.com/india/",
# "Elections": "https://www.ndtv.com/elections/elections-news/",
# "Latest": "https://www.ndtv.com/latest/",
# "Cities": "https://www.ndtv.com/cities/",
# "Education": "https://www.ndtv.com/education/",
# "Trends": "https://www.ndtv.com/trends",
# "Offbeat": "https://www.ndtv.com/offbeat/",
# "South": "https://www.ndtv.com/south/"
# }
# if selected_category:
# st.write(f"Scraping news for {selected_category} category...")
# news_data = scrape_and_summarize(category_urls[selected_category])
# for news_item in news_data:
# st.subheader(news_item["headline"])
# st.write("News Text:")
# st.write(news_item["news_text"])
# st.write("Link:", news_item["link"])
# st.write("---")
# import streamlit as st
# from bs4 import BeautifulSoup
# import requests
# from joblib import Parallel, delayed
# def get_news_text(url):
# page = requests.get(url)
# soup = BeautifulSoup(page.text, 'html.parser')
# news_paragraphs = soup.find_all('p')[:2]
# news_text = '\n'.join([p.text.strip() for p in reversed(news_paragraphs)])
# return news_text
# def scrape_page(url_pattern, tag_name, page_num):
# r = requests.get(f'{url_pattern}{page_num}')
# soup = BeautifulSoup(r.text, 'html.parser')
# news_items = soup.find_all(tag_name)
# results = []
# for item in news_items:
# headline = item.text.strip()
# link = item.a['href']
# news_text = get_news_text(link)
# results.append((headline, link, news_text))
# return results
# def scrape_category(url_pattern, tag_name, pages):
# results = Parallel(n_jobs=32, verbose=100)(delayed(scrape_page)(url_pattern, tag_name, page_num) for page_num in range(1, pages + 1))
# news_data = set()
# for page_result in results:
# for item in page_result:
# news_data.add(item)
# return news_data
# def display_news(category_data):
# for headline, link, news_text in category_data:
# st.write("**Headline:**", headline)
# st.write("**News Text:**", news_text)
# # st.markdown(f"[Read more]({link})")
# st.write('<a style="background-color: #2C3E50; color: white; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; border-radius: 5px;" href="'+link+'" target="_blank">Read more</a>', unsafe_allow_html=True)
# st.write("---")
# def display_news(category_data):
# for headline, link, news_text in category_data:
# st.markdown(f"<h2 style='color: white; font-weight: bold;'>{headline}</h2>", unsafe_allow_html=True)
# st.markdown(f"<p style='color: white;'>{news_text}</p>", unsafe_allow_html=True)
# st.write('<a style="background-color: #2C3E50; color: white; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; border-radius: 5px;" href="'+link+'" target="_blank">Read more</a>', unsafe_allow_html=True)
# st.write("---")
# def main():
# import streamlit as st
# st.markdown(
# """
# <style>
# @import url('https://fonts.googleapis.com/css2?family=Nasalization&display=swap');
# .title {
# color: white;
# font-size: 36px;
# font-family: 'Nasalization', sans-serif;
# font-weight: bold;
# text-align: center;
# margin-bottom: 20px;
# }
# .subheader {
# color: white;
# font-size: 18px;
# font-family: 'Nasalization', sans-serif;
# text-align: center;
# }
# </style>
# """,
# unsafe_allow_html=True
# )
# st.markdown('<p class="title">News Aggregator</p>', unsafe_allow_html=True)
# st.markdown('<p class="subheader">A project by Abhas Jaiswal</p>', unsafe_allow_html=True)
# category = st.selectbox("Select Category", ["India", "Latest", "Cities", "Education", "Trending", "Offbeat", "South"])
# if category == "India":
# news_data = scrape_category('https://www.ndtv.com/india/page-', 'h2', 14)
# elif category == "Latest":
# news_data = scrape_category('https://www.ndtv.com/latest/page-', 'h2', 8)
# elif category == "Cities":
# news_data = scrape_category('https://www.ndtv.com/cities/page-', 'h2', 14)
# elif category == "Education":
# news_data = scrape_category('https://www.ndtv.com/education/page-', 'h2', 14)
# elif category == "Trending":
# news_data = scrape_category('https://www.ndtv.com/trends', 'h3', 1)
# elif category == "Offbeat":
# news_data = scrape_category('https://www.ndtv.com/offbeat/page-', 'h2', 14)
# elif category == "South":
# news_data = scrape_category('https://www.ndtv.com/south/page-', 'h2', 14)
# else:
# st.error("Invalid category selected.")
# display_news(news_data)
# if __name__ == "__main__":
# main()
# import streamlit as st
# from bs4 import BeautifulSoup
# import requests
# from joblib import Parallel, delayed
# import time
# # Function to fetch news text from a given URL
# def get_news_text(url):
# page = requests.get(url)
# soup = BeautifulSoup(page.text, 'html.parser')
# news_paragraphs = soup.find_all('p')[:2]
# news_text = '\n'.join([p.text.strip() for p in reversed(news_paragraphs)])
# return news_text
# # Function to scrape news items from a given page URL
# def scrape_page(url_pattern, tag_name, page_num):
# try:
# r = requests.get(f'{url_pattern}{page_num}')
# soup = BeautifulSoup(r.text, 'html.parser')
# news_items = soup.find_all(tag_name)
# results = []
# for item in news_items:
# headline = item.text.strip()
# link = item.a['href']
# news_text = get_news_text(link)
# results.append((headline, link, news_text))
# return results
# except Exception as e:
# st.error(f"Error occurred while scraping page {page_num}: {e}")
# return []
# # Function to scrape multiple pages of a category
# @st.cache
# def scrape_category(url_pattern, tag_name, pages):
# start_time = time.time()
# results = Parallel(n_jobs=8)(delayed(scrape_page)(url_pattern, tag_name, page_num) for page_num in range(1, pages + 1))
# news_data = set()
# for page_result in results:
# for item in page_result:
# news_data.add(item)
# end_time = time.time()
# return news_data, end_time - start_time
# # Function to display news data
# def display_news(category_data):
# for headline, link, news_text in category_data:
# st.markdown(f"<h2 style='color: white; font-weight: bold;'>{headline}</h2>", unsafe_allow_html=True)
# st.markdown(f"<p style='color: white;'>{news_text}</p>", unsafe_allow_html=True)
# st.write('<a style="background-color: #2C3E50; color: white; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; border-radius: 5px;" href="'+link+'" target="_blank">Read more</a>', unsafe_allow_html=True)
# st.write("---")
# # Main function
# def main():
# st.markdown(
# """
# <style>
# @import url('https://fonts.googleapis.com/css2?family=Nasalization&display=swap');
# .title {
# color: white;
# font-size: 36px;
# font-family: 'Nasalization', sans-serif;
# font-weight: bold;
# text-align: center;
# margin-bottom: 20px;
# }
# .subheader {
# color: white;
# font-size: 18px;
# font-family: 'Nasalization', sans-serif;
# text-align: center;
# }
# </style>
# """,
# unsafe_allow_html=True
# )
# st.markdown('<p class="title">News Aggregator</p>', unsafe_allow_html=True)
# st.markdown('<p class="subheader">A project by Abhas Jaiswal</p>', unsafe_allow_html=True)
# category = st.selectbox("Select Category", ["India", "Latest", "Cities", "Education", "Trending", "Offbeat", "South"])
# if category:
# with st.spinner(f"Fetching {category} news..."):
# if category == "India":
# news_data = scrape_category('https://www.ndtv.com/india/page-', 'h2', 14)
# elif category == "Latest":
# news_data = scrape_category('https://www.ndtv.com/latest/page-', 'h2', 8)
# elif category == "Cities":
# news_data = scrape_category('https://www.ndtv.com/cities/page-', 'h2', 14)
# elif category == "Education":
# news_data = scrape_category('https://www.ndtv.com/education/page-', 'h2', 14)
# elif category == "Trending":
# news_data = scrape_category('https://www.ndtv.com/trends', 'h3', 1)
# elif category == "Offbeat":
# news_data = scrape_category('https://www.ndtv.com/offbeat/page-', 'h2', 14)
# elif category == "South":
# news_data = scrape_category('https://www.ndtv.com/south/page-', 'h2', 14)
# else:
# st.error("Invalid category selected.")
# display_news(news_data)
# if __name__ == "__main__":
# main()
import streamlit as st
from bs4 import BeautifulSoup
import requests
from joblib import Parallel, delayed
import time
def get_news_text(url):
try:
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
news_paragraphs = soup.find_all('p')[:2]
news_text = '\n'.join([p.text.strip() for p in reversed(news_paragraphs)])
return news_text
except Exception as e:
st.error(f"Error fetching news text: {str(e)}")
return ""
def scrape_page(url_pattern, tag_name, page_num):
try:
r = requests.get(f'{url_pattern}{page_num}',timeout=30)
soup = BeautifulSoup(r.text, 'html.parser')
news_items = soup.find_all(tag_name)
results = []
for item in news_items:
headline = item.text.strip()
link = item.a['href']
news_text = get_news_text(link)
results.append((headline, link, news_text))
return results
except Exception as e:
st.error(f"Error scraping page {page_num}: {str(e)}")
return []
def scrape_category(url_pattern, tag_name, pages):
if pages == 1: # If only one page, avoid parallelism
results = [scrape_page(url_pattern, tag_name, 1)]
else:
results = Parallel(n_jobs=32, verbose=100)(delayed(scrape_page)(url_pattern, tag_name, page_num) for page_num in range(1, pages + 1))
news_data = set()
for page_result in results:
for item in page_result:
news_data.add(item)
return news_data
def display_news(category_data):
for headline, link, news_text in category_data:
st.markdown(f"<h2 style='color: white; font-weight: bold;'>{headline}</h2>", unsafe_allow_html=True)
st.markdown(f"<p style='color: white;'>{news_text}</p>", unsafe_allow_html=True)
st.write('<a style="background-color: #2C3E50; color: white; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; border-radius: 5px;" href="'+link+'" target="_blank">Read more</a>', unsafe_allow_html=True)
st.write("---")
def main():
st.markdown(
"""
<style>
@import url('https://fonts.googleapis.com/css2?family=Nasalization&display=swap');
.title {
color: white;
font-size: 36px;
font-family: 'Nasalization', sans-serif;
font-weight: bold;
text-align: center;
margin-bottom: 20px;
}
.subheader {
color: white;
font-size: 18px;
font-family: 'Nasalization', sans-serif;
text-align: center;
}
</style>
""",
unsafe_allow_html=True
)
st.markdown('<p class="title">News Aggregator</p>', unsafe_allow_html=True)
st.markdown('<p class="subheader">A project by Abhas Jaiswal</p>', unsafe_allow_html=True)
category = st.selectbox("Select Category", ["India", "Latest", "Cities", "Education", "Trending", "Offbeat", "South"])
if category == "India":
news_data = scrape_category('https://www.ndtv.com/india/page-', 'h2', 14)
elif category == "Latest":
news_data = scrape_category('https://www.ndtv.com/latest/page-', 'h2', 8)
elif category == "Cities":
news_data = scrape_category('https://www.ndtv.com/cities/page-', 'h2', 14)
elif category == "Education":
news_data = scrape_category('https://www.ndtv.com/education/page-', 'h2', 14)
elif category == "Trending":
news_data = scrape_category('https://www.ndtv.com/trends', 'h3', 1)
elif category == "Offbeat":
news_data = scrape_category('https://www.ndtv.com/offbeat/page-', 'h2', 14)
elif category == "South":
news_data = scrape_category('https://www.ndtv.com/south/page-', 'h2', 14)
else:
st.error("Invalid category selected.")
display_news(news_data)
if __name__ == "__main__":
main()