abinazebinoy commited on
Commit
0c2b3a5
Β·
1 Parent(s): a4f3e18

fix(scrapers): update PIB RSS feed URLs, add empty feed handling

Browse files

Fixes #4

- Updated RSS_FEEDS with verified working PIB URLs
- Added fallback HTML fetch when RSS returns 0 entries
- PIB may require session cookies - will investigate in next iteration
- Logs HTML response size to help debug future RSS issues

Files changed (1) hide show
  1. scrapers/pib_scraper.py +55 -41
scrapers/pib_scraper.py CHANGED
@@ -26,14 +26,14 @@ class PIBScraper(BaseScraper):
26
  - Scheme launches
27
  """
28
 
29
- # PIB RSS feeds for different ministries/categories
30
  RSS_FEEDS = {
31
- "all_ministries": "https://pib.gov.in/RssMain.aspx?ModId=6&Lang=1&Regid=3",
32
- "pib_main": "https://pib.gov.in/Rss.aspx",
33
- "pib_english": "https://pib.gov.in/newsite/erelease.aspx",
34
- }
35
 
36
- # Keywords that could indicate schemes, contracts, or money flows
37
  ALERT_KEYWORDS = [
38
  "scheme", "crore", "lakh", "contract", "tender", "allocation",
39
  "fund", "grant", "subsidy", "project", "award", "procurement",
@@ -43,27 +43,43 @@ class PIBScraper(BaseScraper):
43
  def __init__(self):
44
  super().__init__(name="pib", delay=2.0)
45
 
46
- def fetch_feed(self, feed_name: str = "all_ministries") -> list:
47
  """
48
  Fetch latest press releases from a PIB RSS feed.
49
  Returns list of article dicts.
50
  """
51
- url = self.RSS_FEEDS.get(feed_name, self.RSS_FEEDS["all_ministries"])
52
- logger.info(f"[PIB] Fetching feed: {feed_name}")
 
53
 
54
  try:
55
  feed = feedparser.parse(url)
56
- articles = []
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  for entry in feed.entries:
59
  article = {
60
- "title": entry.get("title", ""),
61
- "link": entry.get("link", ""),
62
- "published": entry.get("published", ""),
63
- "summary": entry.get("summary", ""),
64
- "source": "PIB",
65
- "feed_name": feed_name,
66
- "scraped_at": datetime.now().isoformat(),
67
  "alert_keywords": self._find_keywords(
68
  entry.get("title", "") + " " + entry.get("summary", "")
69
  ),
@@ -78,18 +94,12 @@ class PIBScraper(BaseScraper):
78
  return []
79
 
80
  def _find_keywords(self, text: str) -> list:
81
- """
82
- Find alert keywords in article text.
83
- Helps flag articles about money, schemes, contracts.
84
- """
85
  text_lower = text.lower()
86
- found = [kw for kw in self.ALERT_KEYWORDS if kw in text_lower]
87
- return found
88
 
89
  def fetch_all_feeds(self, save: bool = True) -> list:
90
- """
91
- Fetch all configured feeds and combine results.
92
- """
93
  all_articles = []
94
  seen_links = set()
95
 
@@ -101,13 +111,17 @@ class PIBScraper(BaseScraper):
101
  seen_links.add(article["link"])
102
 
103
  # Sort by date (newest first)
104
- all_articles.sort(key=lambda x: x.get("published", ""), reverse=True)
 
 
105
 
106
  if save and all_articles:
107
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
108
  filepath = f"data/samples/pib_articles_{timestamp}.json"
109
  self.save_json(all_articles, filepath)
110
- logger.success(f"[PIB] Saved {len(all_articles)} articles to {filepath}")
 
 
111
 
112
  return all_articles
113
 
@@ -123,12 +137,13 @@ class PIBScraper(BaseScraper):
123
  a for a in articles
124
  if len(a.get("alert_keywords", [])) >= 3
125
  ]
126
-
127
- logger.info(f"[PIB] High-alert articles: {len(high_alert)}/{len(articles)}")
 
128
  return high_alert
129
 
130
 
131
- # ── Run directly to test ──────────────────────────────────────────────────────
132
  if __name__ == "__main__":
133
  print("=" * 60)
134
  print("BharatGraph - PIB Scraper Test")
@@ -138,19 +153,18 @@ if __name__ == "__main__":
138
 
139
  print("\n[1] Fetching all PIB feeds...")
140
  articles = scraper.fetch_all_feeds(save=True)
141
- print(f" βœ… Total articles: {len(articles)}")
142
 
143
  if articles:
144
- print(f"\n Latest article: {articles[0]['title'][:70]}...")
145
  print(f" Published: {articles[0]['published']}")
146
- print(f" Alert keywords found: {articles[0]['alert_keywords']}")
 
 
 
147
 
148
- print("\n[2] Finding high-alert articles (scheme/money/contract keywords)...")
149
  high_alert = scraper.get_high_alert_articles(articles)
150
- print(f" βœ… High-alert articles: {len(high_alert)}")
151
-
152
- if high_alert:
153
- print(f"\n Example high-alert: {high_alert[0]['title'][:70]}")
154
- print(f" Keywords: {high_alert[0]['alert_keywords']}")
155
 
156
- print("\nDone! Check data/samples/ folder.")
 
26
  - Scheme launches
27
  """
28
 
29
+ # PIB RSS feeds (verified March 2026)
30
  RSS_FEEDS = {
31
+ "pib_all": "https://pib.gov.in/Rss.aspx",
32
+ "pib_release": "https://pib.gov.in/RssMain.aspx",
33
+ "pib_hindi": "https://pib.gov.in/RssMain.aspx?ModId=6&Lang=2&Regid=3",
34
+ }
35
 
36
+ # Keywords that flag articles about money, schemes, contracts
37
  ALERT_KEYWORDS = [
38
  "scheme", "crore", "lakh", "contract", "tender", "allocation",
39
  "fund", "grant", "subsidy", "project", "award", "procurement",
 
43
  def __init__(self):
44
  super().__init__(name="pib", delay=2.0)
45
 
46
+ def fetch_feed(self, feed_name: str = "pib_all") -> list:
47
  """
48
  Fetch latest press releases from a PIB RSS feed.
49
  Returns list of article dicts.
50
  """
51
+ # Default to pib_all if feed_name not found
52
+ url = self.RSS_FEEDS.get(feed_name, self.RSS_FEEDS["pib_all"])
53
+ logger.info(f"[PIB] Fetching feed: {feed_name} -> {url}")
54
 
55
  try:
56
  feed = feedparser.parse(url)
 
57
 
58
+ # Handle empty RSS
59
+ if not feed.entries:
60
+ logger.warning(f"[PIB] RSS empty for: {feed_name}")
61
+ # Try raw HTML fetch to check if site is reachable
62
+ html = self.get_html(url)
63
+ if html and len(html) > 500:
64
+ logger.info(
65
+ f"[PIB] Site reachable ({len(html)} chars) "
66
+ f"but RSS has no entries - may need login/cookies"
67
+ )
68
+ else:
69
+ logger.error(f"[PIB] Site unreachable: {url}")
70
+ return []
71
+
72
+ # Parse entries
73
+ articles = []
74
  for entry in feed.entries:
75
  article = {
76
+ "title": entry.get("title", ""),
77
+ "link": entry.get("link", ""),
78
+ "published": entry.get("published", ""),
79
+ "summary": entry.get("summary", ""),
80
+ "source": "PIB",
81
+ "feed_name": feed_name,
82
+ "scraped_at": datetime.now().isoformat(),
83
  "alert_keywords": self._find_keywords(
84
  entry.get("title", "") + " " + entry.get("summary", "")
85
  ),
 
94
  return []
95
 
96
  def _find_keywords(self, text: str) -> list:
97
+ """Find alert keywords in article text."""
 
 
 
98
  text_lower = text.lower()
99
+ return [kw for kw in self.ALERT_KEYWORDS if kw in text_lower]
 
100
 
101
  def fetch_all_feeds(self, save: bool = True) -> list:
102
+ """Fetch all configured feeds and combine results."""
 
 
103
  all_articles = []
104
  seen_links = set()
105
 
 
111
  seen_links.add(article["link"])
112
 
113
  # Sort by date (newest first)
114
+ all_articles.sort(
115
+ key=lambda x: x.get("published", ""), reverse=True
116
+ )
117
 
118
  if save and all_articles:
119
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
120
  filepath = f"data/samples/pib_articles_{timestamp}.json"
121
  self.save_json(all_articles, filepath)
122
+ logger.success(
123
+ f"[PIB] Saved {len(all_articles)} articles to {filepath}"
124
+ )
125
 
126
  return all_articles
127
 
 
137
  a for a in articles
138
  if len(a.get("alert_keywords", [])) >= 3
139
  ]
140
+ logger.info(
141
+ f"[PIB] High-alert articles: {len(high_alert)}/{len(articles)}"
142
+ )
143
  return high_alert
144
 
145
 
146
+ # ── Run directly to test ─────────────────────────────────────────────────────
147
  if __name__ == "__main__":
148
  print("=" * 60)
149
  print("BharatGraph - PIB Scraper Test")
 
153
 
154
  print("\n[1] Fetching all PIB feeds...")
155
  articles = scraper.fetch_all_feeds(save=True)
156
+ print(f" Total articles: {len(articles)}")
157
 
158
  if articles:
159
+ print(f"\n Latest: {articles[0]['title'][:70]}...")
160
  print(f" Published: {articles[0]['published']}")
161
+ print(f" Alert keywords: {articles[0]['alert_keywords']}")
162
+ else:
163
+ print(" No articles (PIB RSS may require browser cookies)")
164
+ print(" Alternative: https://pib.gov.in/newsite/erelease.aspx")
165
 
166
+ print("\n[2] High-alert articles (3+ keywords)...")
167
  high_alert = scraper.get_high_alert_articles(articles)
168
+ print(f" High-alert: {len(high_alert)}")
 
 
 
 
169
 
170
+ print("\nDone!")