Spaces:
Sleeping
Sleeping
Download src/scraper.py from arki3212/multilingual-scraper: direct link, hf CLI and curl.
- Browser
- Download file 4.34 kB
-
https://huggingface.co/spaces/arki3212/multilingual-scraper/resolve/main/src/scraper.py
- Command line
-
hf download hf://spaces/arki3212/multilingual-scraper/src/scraper.py
-
curl -L -o scraper.py https://huggingface.co/spaces/arki3212/multilingual-scraper/resolve/main/src/scraper.py
4.34 kB
| import httpx | |
| import feedparser | |
| from bs4 import BeautifulSoup | |
| from typing import List, Dict, Optional | |
| import time | |
| from urllib.parse import urljoin, urlparse | |
| class NewsScraper: | |
| def __init__(self): | |
| self.headers = { | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36", | |
| "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8", | |
| "Accept-Language": "en-US,en;q=0.9", | |
| } | |
| async def fetch_url(self, url: str, client: Optional[httpx.AsyncClient] = None) -> Optional[str]: | |
| try: | |
| if client: | |
| response = await client.get(url) | |
| response.raise_for_status() | |
| return response.text | |
| else: | |
| async with httpx.AsyncClient(headers=self.headers, follow_redirects=True, timeout=15.0) as local_client: | |
| response = await local_client.get(url) | |
| response.raise_for_status() | |
| return response.text | |
| except: return None | |
| def parse_rss(self, rss_content: str) -> List[str]: | |
| feed = feedparser.parse(rss_content) | |
| return [entry.link for entry in feed.entries] | |
| def extract_links_from_html(self, html_content: str, base_url: str) -> List[str]: | |
| soup = BeautifulSoup(html_content, "html.parser") | |
| links = [] | |
| domain = urlparse(base_url).netloc | |
| for a in soup.find_all("a", href=True): | |
| href = a["href"] | |
| full_url = urljoin(base_url, href) | |
| parsed_url = urlparse(full_url) | |
| if parsed_url.netloc == domain and len(parsed_url.path) > 10: | |
| # Exclude nav/taxonomy pages but NOT pagination — pagination is handled by scrape_source | |
| if not any(x in full_url.lower() for x in ["/tag/", "/category/", "/author/", "/search/"]): | |
| links.append(full_url) | |
| return list(set(links)) | |
| async def scrape_api(self, source_config: Dict, client: httpx.AsyncClient) -> List[str]: | |
| api_name = source_config['name'] | |
| api_key = os.getenv(source_config.get("api_key_env", "")) | |
| if not api_key: return [] | |
| links = [] | |
| try: | |
| if api_name == "thenewsapi": | |
| url = f"https://api.thenewsapi.com/v1/news/all?api_token={api_key}&search=ethiopia&language=en" | |
| resp = await client.get(url) | |
| if resp.status_code == 200: | |
| data = resp.json() | |
| links = [item['url'] for item in data.get('data', [])] | |
| elif api_name == "gnews": | |
| url = f"https://gnews.io/api/v4/search?q=ethiopia&lang=en&token={api_key}" | |
| resp = await client.get(url) | |
| if resp.status_code == 200: | |
| data = resp.json() | |
| links = [item['url'] for item in data.get('articles', [])] | |
| elif api_name == "worldnewsapi": | |
| url = f"https://api.worldnewsapi.com/search-news?text=ethiopia&language=en&api-key={api_key}" | |
| resp = await client.get(url) | |
| if resp.status_code == 200: | |
| data = resp.json() | |
| links = [item['url'] for item in data.get('news', [])] | |
| except Exception as e: | |
| print(f"Error scraping API {api_name}: {e}") | |
| return links | |
| async def scrape_source(self, source_config: Dict, client: httpx.AsyncClient) -> List[str]: | |
| if source_config.get("type") == "api": | |
| return await self.scrape_api(source_config, client) | |
| source_name = source_config['name'] | |
| all_links = [] | |
| rss_url = source_config.get("rss_url") | |
| if rss_url: | |
| rss_content = await self.fetch_url(rss_url, client) | |
| if rss_content: all_links.extend(self.parse_rss(rss_content)) | |
| category_url = source_config["url"] | |
| for page in range(1, 4): | |
| url = f"{category_url}?page={page}" if page > 1 else category_url | |
| content = await self.fetch_url(url, client) | |
| if not content: break | |
| all_links.extend(self.extract_links_from_html(content, url)) | |
| return list(set(all_links)) | |