Add news pipeline: hourly scraper + Gemini summarizer in compose
Some checks failed
build-and-deploy / build (push) Failing after 4s
Some checks failed
build-and-deploy / build (push) Failing after 4s
Vendor the newsPipeline scraper + summarizer into the repo and wire them into
docker-compose against the EXISTING osint-db (no second Postgres), replacing
the upstream k8s CronJobs with in-compose wall-clock loops (:00 scrape, :05
summarize).
- news/scraper: vendored Scrapy project (257 RSS feeds) + hourly loop
scheduler (run_news_scraper.py)
- news/summerizer: vendored Gemini map-reduce summarizer, cleaned:
* fix broken google-genai response handling (_extract_text, defensive)
* fix malformed INSERT/GRANT query in save_summary_to_db
* OSINT-neutral default MAP_PROMPT; futures/markets language gated behind
INCLUDE_FUTURES=0 (yfinance lazy-imported)
* env-configurable model, batch size, lookback window
+ hourly loop scheduler (run_news_summarizer.py, :05)
- alembic 003_news: idempotent articles + article_summaries tables
- API: GET /api/news and GET /api/news/summaries (+ models, schemas)
- tests/test_api_news.py: 5 DB-backed contract tests (all pass vs real PG)
- docs/news.md + .env.example updates
Both services run under the `ingest` compose profile (matching the
ingester/camera-scraper pattern) and build arm64 on the Pi via the existing
Forgejo CI workflow. telebot left out of scope (reserved env only).
This commit is contained in:
parent
172273bed6
commit
91f436390b
27 changed files with 1772 additions and 2 deletions
19
news/scraper/.dockerignore
Normal file
19
news/scraper/.dockerignore
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
# Secrets and Config
|
||||
.env
|
||||
*.key
|
||||
*.pem
|
||||
|
||||
# Python artifacts
|
||||
**/__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
.pytest_cache/
|
||||
|
||||
# Scrapy runtime output (created inside the container at /app/data)
|
||||
data/
|
||||
*.jsonl
|
||||
.scrapy/
|
||||
|
||||
# Git
|
||||
.git
|
||||
.gitignore
|
||||
4
news/scraper/.gitignore
vendored
Normal file
4
news/scraper/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
# Scrapy runtime output (only created when run locally, not in the container)
|
||||
data/
|
||||
*.jsonl
|
||||
.scrapy/
|
||||
44
news/scraper/Dockerfile
Normal file
44
news/scraper/Dockerfile
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
FROM python:3.12-slim AS builder
|
||||
|
||||
# Prevent Python from writing .pyc files and enable unbuffered logging
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /install
|
||||
|
||||
# Install system dependencies required for building lxml and other Scrapy deps
|
||||
RUN apt-get update && apt-get install -y \
|
||||
gcc \
|
||||
libxml2-dev \
|
||||
libxslt-dev \
|
||||
libffi-dev \
|
||||
libssl-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install dependencies to a temporary location
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
|
||||
|
||||
|
||||
# --- Stage 2: Runtime ---
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy the installed python packages from the builder stage
|
||||
COPY --from=builder /install /usr/local
|
||||
|
||||
# Copy the project files
|
||||
COPY . .
|
||||
|
||||
|
||||
# Security: Run as a non-privileged user
|
||||
RUN useradd -m scraper
|
||||
RUN mkdir -p /app/data && chown -R scraper:scraper /app/data
|
||||
USER scraper
|
||||
|
||||
# Set the entrypoint to the scrapy command
|
||||
ENTRYPOINT ["scrapy"]
|
||||
|
||||
# Default command if none is provided
|
||||
CMD ["crawl", "articles"]
|
||||
0
news/scraper/newsScraper/__init__.py
Normal file
0
news/scraper/newsScraper/__init__.py
Normal file
12
news/scraper/newsScraper/items.py
Normal file
12
news/scraper/newsScraper/items.py
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
# Define here the models for your scraped items
|
||||
#
|
||||
# See documentation in:
|
||||
# https://docs.scrapy.org/en/latest/topics/items.html
|
||||
|
||||
import scrapy
|
||||
|
||||
|
||||
class NewsscraperItem(scrapy.Item):
|
||||
# define the fields for your item here like:
|
||||
# name = scrapy.Field()
|
||||
pass
|
||||
113
news/scraper/newsScraper/middlewares.py
Normal file
113
news/scraper/newsScraper/middlewares.py
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
# Define here the models for your spider middleware
|
||||
#
|
||||
# See documentation in:
|
||||
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
|
||||
|
||||
from scrapy import signals
|
||||
|
||||
# useful for handling different item types with a single interface
|
||||
from itemadapter import ItemAdapter
|
||||
|
||||
|
||||
class NewsscraperSpiderMiddleware:
|
||||
# Not all methods need to be defined. If a method is not defined,
|
||||
# scrapy acts as if the spider middleware does not modify the
|
||||
# passed objects.
|
||||
|
||||
@classmethod
|
||||
def from_crawler(cls, crawler):
|
||||
# This method is used by Scrapy to create your spiders.
|
||||
s = cls()
|
||||
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
|
||||
return s
|
||||
|
||||
def process_spider_input(self, response, spider):
|
||||
# Called for each response that goes through the spider
|
||||
# middleware and into the spider.
|
||||
|
||||
# Should return None or raise an exception.
|
||||
return None
|
||||
|
||||
def process_spider_output(self, response, result, spider):
|
||||
# Called with the results returned from the Spider, after
|
||||
# it has processed the response.
|
||||
|
||||
# Must return an iterable of Request, or item objects.
|
||||
for i in result:
|
||||
yield i
|
||||
|
||||
def process_spider_exception(self, response, exception, spider):
|
||||
# Called when a spider or process_spider_input() method
|
||||
# (from other spider middleware) raises an exception.
|
||||
|
||||
# Should return either None or an iterable of Request or item objects.
|
||||
pass
|
||||
|
||||
async def process_start(self, start):
|
||||
# Called with an async iterator over the spider start() method or the
|
||||
# matching method of an earlier spider middleware.
|
||||
async for item_or_request in start:
|
||||
yield item_or_request
|
||||
|
||||
def spider_opened(self, spider):
|
||||
spider.logger.info("Spider opened: %s" % spider.name)
|
||||
|
||||
|
||||
class NewsscraperDownloaderMiddleware:
|
||||
# Not all methods need to be defined. If a method is not defined,
|
||||
# scrapy acts as if the downloader middleware does not modify the
|
||||
# passed objects.
|
||||
|
||||
@classmethod
|
||||
def from_crawler(cls, crawler):
|
||||
# This method is used by Scrapy to create your spiders.
|
||||
s = cls()
|
||||
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
|
||||
return s
|
||||
|
||||
def process_request(self, request, spider):
|
||||
# Called for each request that goes through the downloader
|
||||
# middleware.
|
||||
|
||||
# Must either:
|
||||
# - return None: continue processing this request
|
||||
# - or return a Response object
|
||||
# - or return a Request object
|
||||
# - or raise IgnoreRequest: process_exception() methods of
|
||||
# installed downloader middleware will be called
|
||||
return None
|
||||
|
||||
def process_response(self, request, response, spider):
|
||||
# Called with the response returned from the downloader.
|
||||
|
||||
# Must either;
|
||||
# - return a Response object
|
||||
# - return a Request object
|
||||
# - or raise IgnoreRequest
|
||||
return response
|
||||
|
||||
def process_exception(self, request, exception, spider):
|
||||
# Called when a download handler or a process_request()
|
||||
# (from other downloader middleware) raises an exception.
|
||||
|
||||
# Must either:
|
||||
# - return None: continue processing this exception
|
||||
# - return a Response object: stops process_exception() chain
|
||||
# - return a Request object: stops process_exception() chain
|
||||
pass
|
||||
|
||||
def spider_opened(self, spider):
|
||||
spider.logger.info("Spider opened: %s" % spider.name)
|
||||
|
||||
class ProxyMiddleware:
|
||||
def __init__(self, proxy_url):
|
||||
self.proxy_url = proxy_url
|
||||
|
||||
@classmethod
|
||||
def from_crawler(cls, crawler):
|
||||
return cls(proxy_url=crawler.settings.get('PROXY_URL'))
|
||||
|
||||
def process_request(self, request, spider):
|
||||
# Only attach the proxy if PROXY_URL was successfully built
|
||||
if self.proxy_url:
|
||||
request.meta['proxy'] = self.proxy_url
|
||||
92
news/scraper/newsScraper/pipelines.py
Normal file
92
news/scraper/newsScraper/pipelines.py
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
# Define your item pipelines here
|
||||
#
|
||||
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
|
||||
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
|
||||
|
||||
import logging
|
||||
import psycopg2
|
||||
import os
|
||||
from scrapy.exceptions import DropItem
|
||||
class PostgresPipeline:
|
||||
|
||||
def __init__(self, db_config):
|
||||
# 1. Store the config
|
||||
self.db_config = db_config
|
||||
# 2. Initialize the set here so it exists when process_item is called
|
||||
self.seen_urls = set()
|
||||
|
||||
@classmethod
|
||||
def from_crawler(cls, crawler):
|
||||
db_config = {
|
||||
'host': crawler.settings.get('DB_HOST'),
|
||||
'database': crawler.settings.get('DB_NAME'),
|
||||
'user': crawler.settings.get('DB_USER'),
|
||||
'password': crawler.settings.get('DB_PASSWORD'),
|
||||
}
|
||||
return cls(db_config=db_config)
|
||||
|
||||
|
||||
|
||||
|
||||
def open_spider(self, spider):
|
||||
# Connect using environment variables
|
||||
self.connection = psycopg2.connect(
|
||||
host=os.getenv('DB_HOST'),
|
||||
database=os.getenv('DB_NAME'),
|
||||
user=os.getenv('DB_USER'),
|
||||
password=os.getenv('DB_PASSWORD'),
|
||||
port=os.getenv('DB_PORT', '5432')
|
||||
)
|
||||
self.cur = self.connection.cursor()
|
||||
|
||||
# Create table if it doesn't exist
|
||||
self.cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS articles (
|
||||
id SERIAL PRIMARY KEY,
|
||||
title TEXT,
|
||||
url TEXT UNIQUE,
|
||||
content TEXT,
|
||||
domain TEXT,
|
||||
timestamp TIMESTAMPTZ
|
||||
)
|
||||
""")
|
||||
self.connection.commit()
|
||||
|
||||
def process_item(self, item, spider):
|
||||
if item ['url'] in self.seen_urls:
|
||||
raise DropItem()
|
||||
try:
|
||||
self.cur.execute("""
|
||||
INSERT INTO articles (title, url, content, domain, timestamp)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
ON CONFLICT (url) DO NOTHING
|
||||
""", (
|
||||
item['title'],
|
||||
item['url'],
|
||||
item['text'],
|
||||
item['domain'],
|
||||
item['timestamp']
|
||||
))
|
||||
if self.cur.rowcount == 0:
|
||||
e = DropItem("Duplicate URL (database conflict)")
|
||||
e.log_level = logging.DEBUG
|
||||
raise e
|
||||
self.connection.commit()
|
||||
return item
|
||||
except Exception as e:
|
||||
spider.logger.error(f"Error saving to Postgres: {e}")
|
||||
self.connection.rollback()
|
||||
raise
|
||||
|
||||
def close_spider(self, spider):
|
||||
self.cur.close()
|
||||
self.connection.close()
|
||||
|
||||
from itemadapter import ItemAdapter
|
||||
|
||||
|
||||
class NewsscraperPipeline:
|
||||
def process_item(self, item, spider):
|
||||
return item
|
||||
|
||||
|
||||
94
news/scraper/newsScraper/settings.py
Normal file
94
news/scraper/newsScraper/settings.py
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import os
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv()
|
||||
|
||||
PROXY_USER = os.getenv('PROXY_USER', '').strip()
|
||||
PROXY_PASS = os.getenv('PROXY_PASS', '').strip()
|
||||
PROXY_ENDPOINT = os.getenv('PROXY_ENDPOINT', '').strip()
|
||||
|
||||
def get_proxy_url():
|
||||
if not PROXY_ENDPOINT:
|
||||
return None
|
||||
endpoint = PROXY_ENDPOINT.replace('http://', '').replace('https://','')
|
||||
|
||||
if PROXY_USER and PROXY_PASS:
|
||||
return f"http://{PROXY_USER}:{PROXY_PASS}@{endpoint}"
|
||||
else:
|
||||
return f"http://{endpoint}"
|
||||
|
||||
PROXY_URL = get_proxy_url()
|
||||
|
||||
DOWNLOADER_MIDDLEWARES = {
|
||||
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110,
|
||||
}
|
||||
|
||||
BOT_NAME = "newsScraper"
|
||||
|
||||
SPIDER_MODULES = ["newsScraper.spiders"]
|
||||
NEWSPIDER_MODULE = "newsScraper.spiders"
|
||||
|
||||
ADDONS = {}
|
||||
|
||||
|
||||
# Crawl responsibly by identifying yourself (and your website) on the user-agent
|
||||
USER_AGENT = os.getenv('USER_AGENT', "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
|
||||
DEFAULT_REQUEST_HEADERS = {
|
||||
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
|
||||
'Accept-Language': 'en-US,en;q=0.5',
|
||||
'Accept-Encoding': 'gzip, deflate, br',
|
||||
'DNT': '1',
|
||||
'Connection': 'keep-alive',
|
||||
'Upgrade-Insecure-Requests': '1',
|
||||
}
|
||||
|
||||
# Obey robots.txt rules
|
||||
ROBOTSTXT_OBEY = True
|
||||
|
||||
# Concurrency and throttling settings
|
||||
CONCURRENT_REQUESTS = os.getenv('CONCURRENT_REQUESTS', '100').strip()
|
||||
CONCURRENT_REQUESTS_PER_DOMAIN = 2
|
||||
DOWNLOAD_DELAY = 3
|
||||
REACTOR_THREADPOOL_MAXSIZE = 100
|
||||
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
|
||||
RETRY_ENABLED = True
|
||||
DOWNLOAD_TIMEOUT = 60
|
||||
AJAXCRAWL_ENABLED = False
|
||||
AUTO_THROTTLE_ENABLED = True
|
||||
AUTOTHROTTLE_ENABLED = True
|
||||
AUTOTHROTTLE_TARGET_CONCURRENCY = 2.0
|
||||
DNSCACHE_ENABLED = True
|
||||
DNSCACHE_SIZE = 20000
|
||||
DNS_TIMEOUT = 20
|
||||
DNS_RESOLVER = 'scrapy.resolver.CachingThreadedResolver'
|
||||
DEPTH_LIMIT = os.getenv('DEPTH_LIMIT', 1)
|
||||
|
||||
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
|
||||
|
||||
|
||||
FEEDS = {
|
||||
'data/hourly_news.jsonl':{
|
||||
'format': 'jsonlines',
|
||||
'encoding': 'utf8',
|
||||
'overwrite': True,
|
||||
}
|
||||
}
|
||||
FEED_EXPORT_ENCODING = "utf-8"
|
||||
|
||||
ITEM_PIPELINES = {
|
||||
'newsScraper.pipelines.PostgresPipeline': 300,
|
||||
}
|
||||
|
||||
# Database Config (These should be in your .env / K8s Secrets)
|
||||
|
||||
DB_HOST = os.getenv('DB_HOST', 'postgres-service')
|
||||
DB_NAME = os.getenv('DB_NAME', 'news_db')
|
||||
DB_USER = os.getenv('DB_USER', 'admin')
|
||||
DB_PASSWORD = os.getenv('DB_PASSWORD')
|
||||
|
||||
db_config = {
|
||||
'host': DB_HOST,
|
||||
'database': DB_NAME,
|
||||
'user': DB_USER,
|
||||
'password': DB_PASSWORD,
|
||||
'port': 5432 # Default postgres port
|
||||
}
|
||||
4
news/scraper/newsScraper/spiders/__init__.py
Normal file
4
news/scraper/newsScraper/spiders/__init__.py
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
# This package will contain the spiders of your Scrapy project
|
||||
#
|
||||
# Please refer to the documentation for information on how to create and manage
|
||||
# your spiders.
|
||||
50
news/scraper/newsScraper/spiders/news_spider.py
Normal file
50
news/scraper/newsScraper/spiders/news_spider.py
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import scrapy
|
||||
from scrapy.spiders import XMLFeedSpider
|
||||
from urllib.parse import urlparse
|
||||
import datetime
|
||||
import re
|
||||
|
||||
class NewsRSSSpider(XMLFeedSpider):
|
||||
name = "articles"
|
||||
iterator = 'xml'
|
||||
itertag = 'item' # Standard RSS tag for an article
|
||||
namespaces = [
|
||||
('dc', 'http://purl.org/dc/elements/1.1/'),
|
||||
('content', 'http://purl.org/rss/1.0/modules/content/'),
|
||||
('media', 'http://search.yahoo.com/mrss/')
|
||||
]
|
||||
|
||||
def __init__(self, filename='urls.txt', *args, **kwargs):
|
||||
super(NewsRSSSpider, self).__init__(*args, **kwargs)
|
||||
with open(filename, 'r') as f:
|
||||
# We filter for RSS feeds only here
|
||||
self.start_urls = [line.strip() for line in f if '/rss' in line or '/feed' in line]
|
||||
|
||||
def parse_node(self, response, node):
|
||||
"""This runs for every <item> found in the RSS XML"""
|
||||
title = node.xpath('title/text()').get()
|
||||
link = node.xpath('link/text()').get()
|
||||
pub_date = node.xpath('pubDate/text()').get()
|
||||
|
||||
# We now yield a Request to the actual article to get the full text
|
||||
# Since these are RSS links, they are usually 'clean' HTML
|
||||
if link:
|
||||
yield scrapy.Request(link, callback=self.parse_article, meta={'title': title, 'date': pub_date})
|
||||
|
||||
def parse_article(self, response):
|
||||
|
||||
title = response.meta.get('title')
|
||||
|
||||
# Greedy search for the main text body
|
||||
article_text = response.xpath('//article//p/text() | //main//p/text() | //div[contains(@class, "body")]//p/text()').getall()
|
||||
pure_text = " ".join(article_text)
|
||||
pure_text = re.sub(r'\s+', ' ', pure_text).strip()
|
||||
|
||||
if len(pure_text) > 300:
|
||||
yield {
|
||||
'title': title,
|
||||
'url': response.url,
|
||||
'text': pure_text,
|
||||
'domain': urlparse(response.url).netloc,
|
||||
'timestamp': datetime.datetime.now().isoformat()
|
||||
}
|
||||
44
news/scraper/requirements.txt
Normal file
44
news/scraper/requirements.txt
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
attrs==25.4.0
|
||||
Automat==25.4.16
|
||||
brotli==1.2.0
|
||||
certifi==2026.1.4
|
||||
cffi==2.0.0
|
||||
charset-normalizer==3.4.4
|
||||
constantly==23.10.4
|
||||
cryptography==46.0.3
|
||||
cssselect==1.3.0
|
||||
defusedxml==0.7.1
|
||||
filelock==3.20.2
|
||||
hyperlink==21.0.0
|
||||
idna==3.11
|
||||
Incremental==24.11.0
|
||||
itemadapter==0.13.1
|
||||
itemloaders==1.3.2
|
||||
jmespath==1.0.1
|
||||
lxml==6.0.2
|
||||
packaging==25.0
|
||||
parsel==1.10.0
|
||||
Protego==0.5.0
|
||||
pyasn1==0.6.1
|
||||
pyasn1_modules==0.4.2
|
||||
pycparser==2.23
|
||||
PyDispatcher==2.0.7
|
||||
pyOpenSSL==25.3.0
|
||||
queuelib==1.8.0
|
||||
requests==2.32.5
|
||||
requests-file==3.0.1
|
||||
Scrapy==2.14.0
|
||||
scrapy-user-agents==0.1.1
|
||||
service-identity==24.2.0
|
||||
tldextract==5.3.1
|
||||
Twisted==25.5.0
|
||||
typing_extensions==4.15.0
|
||||
ua-parser==1.0.1
|
||||
ua-parser-builtins==202601
|
||||
urllib3==2.6.3
|
||||
user-agents==2.2.0
|
||||
w3lib==2.3.1
|
||||
zope.interface==8.1.1
|
||||
psycopg2-binary==2.9.11
|
||||
python-dotenv==0.20.0
|
||||
scrapy-playwright==0.0.45
|
||||
67
news/scraper/run_news_scraper.py
Normal file
67
news/scraper/run_news_scraper.py
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Scheduler loop for the news scraper — hourly scrape at minute :00.
|
||||
|
||||
Replaces the k8s CronJob (`0 * * * *`) with an in-compose loop so the whole
|
||||
news pipeline lives inside docker-compose. Each iteration:
|
||||
|
||||
1. (optionally, on first boot) runs the Scrapy crawl once to seed data fast
|
||||
2. sleeps until the next :NEWS_SCRAPE_MINUTE wall-clock boundary
|
||||
|
||||
Because the loop is serial, a crawl that overruns its hour simply delays the
|
||||
next run to the following boundary — two crawls never overlap.
|
||||
|
||||
Env (all optional, 12-factor):
|
||||
NEWS_SCRAPE_MINUTE minute of the hour to fire (default 0)
|
||||
NEWS_SCRAPE_RUN_ON_START "1" to crawl once immediately on boot (default 1)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger("news.scraper")
|
||||
|
||||
MINUTE = int(os.getenv("NEWS_SCRAPE_MINUTE", "0"))
|
||||
RUN_ON_START = os.getenv("NEWS_SCRAPE_RUN_ON_START", "1").lower() in ("1", "true", "yes")
|
||||
|
||||
CRAWL_CMD = ["scrapy", "crawl", "articles"]
|
||||
|
||||
|
||||
def seconds_until_next(minute: int) -> float:
|
||||
"""Seconds until the next occurrence of ``minute`` past the hour (local time)."""
|
||||
now = datetime.datetime.now()
|
||||
nxt = now.replace(minute=minute, second=0, microsecond=0) + datetime.timedelta(hours=1)
|
||||
return (nxt - now).total_seconds()
|
||||
|
||||
|
||||
def run_crawl() -> None:
|
||||
logger.info("scrape starting at %s", datetime.datetime.now().isoformat(timespec="seconds"))
|
||||
try:
|
||||
proc = subprocess.run(CRAWL_CMD, cwd="/app")
|
||||
logger.info("scrape finished rc=%s", proc.returncode)
|
||||
except Exception: # noqa: BLE001 — keep the loop alive across failures
|
||||
logger.exception("scrape failed")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logger.info(
|
||||
"news scraper loop starting (minute=%s, run_on_start=%s)",
|
||||
MINUTE, RUN_ON_START,
|
||||
)
|
||||
if RUN_ON_START:
|
||||
run_crawl()
|
||||
while True:
|
||||
delay = seconds_until_next(MINUTE)
|
||||
logger.info("next scrape at :%02d (in %.0fs)", MINUTE, delay)
|
||||
time.sleep(delay)
|
||||
run_crawl()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
11
news/scraper/scrapy.cfg
Normal file
11
news/scraper/scrapy.cfg
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# Automatically created by: scrapy startproject
|
||||
#
|
||||
# For more information about the [deploy] section see:
|
||||
# https://scrapyd.readthedocs.io/en/latest/deploy.html
|
||||
|
||||
[settings]
|
||||
default = newsScraper.settings
|
||||
|
||||
[deploy]
|
||||
#url = http://localhost:6800/
|
||||
project = newsScraper
|
||||
257
news/scraper/urls.txt
Normal file
257
news/scraper/urls.txt
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
# --- NORTH AMERICA ---
|
||||
# USA
|
||||
https://www.npr.org
|
||||
https://www.pbs.org/newshour
|
||||
https://www.usatoday.com
|
||||
https://www.cbsnews.com
|
||||
https://www.nbcnews.com
|
||||
|
||||
# Canada
|
||||
https://www.cbc.ca/news
|
||||
https://www.ctvnews.ca
|
||||
https://globalnews.ca
|
||||
https://nationalpost.com
|
||||
https://www.thestar.com
|
||||
|
||||
# Mexico
|
||||
https://www.eluniversal.com.mx
|
||||
https://www.milenio.com
|
||||
https://www.jornada.com.mx
|
||||
https://www.excelsior.com.mx
|
||||
https://aristeguinoticias.com
|
||||
|
||||
# --- SOUTH AMERICA ---
|
||||
# Brazil
|
||||
https://g1.globo.com
|
||||
https://www.uol.com.br
|
||||
https://agenciabrasil.ebc.com.br
|
||||
https://www.metropoles.com
|
||||
https://www.terra.com.br/noticias
|
||||
|
||||
# Argentina
|
||||
https://www.infobae.com
|
||||
https://www.clarin.com
|
||||
https://www.lanacion.com.ar
|
||||
https://www.pagina12.com.ar
|
||||
https://www.cronista.com
|
||||
|
||||
# Colombia
|
||||
https://www.eltiempo.com
|
||||
https://www.elespectador.com
|
||||
https://www.semana.com
|
||||
https://www.bluradio.com
|
||||
https://www.rcnradio.com
|
||||
|
||||
# --- EUROPE ---
|
||||
# United Kingdom
|
||||
https://www.bbc.com/news
|
||||
https://www.theguardian.com/uk
|
||||
https://news.sky.com
|
||||
https://www.independent.co.uk
|
||||
https://metro.co.uk
|
||||
|
||||
# France
|
||||
https://www.france24.com/en
|
||||
https://www.lefigaro.fr
|
||||
https://www.20minutes.fr
|
||||
https://www.francetvinfo.fr
|
||||
https://www.lemonde.fr
|
||||
|
||||
# Germany
|
||||
https://www.dw.com/en
|
||||
https://www.tagesschau.de
|
||||
https://www.spiegel.de
|
||||
https://www.zeit.de
|
||||
https://www.bild.de
|
||||
|
||||
# Spain
|
||||
https://elpais.com
|
||||
https://www.elmundo.es
|
||||
https://www.rtve.es/noticias
|
||||
https://www.20minutos.es
|
||||
https://www.elconfidencial.com
|
||||
|
||||
# Italy
|
||||
https://www.ansa.it
|
||||
https://www.corriere.it
|
||||
https://www.repubblica.it
|
||||
https://www.lastampa.it
|
||||
https://tg24.sky.it
|
||||
|
||||
# Russia (State & Independent mix)
|
||||
https://tass.com
|
||||
https://www.interfax.ru
|
||||
https://www.rt.com
|
||||
https://www.themoscowtimes.com
|
||||
https://meduza.io/en
|
||||
|
||||
# --- ASIA ---
|
||||
# China
|
||||
https://www.xinhuanet.com/english
|
||||
https://www.chinadaily.com.cn
|
||||
https://www.globaltimes.cn
|
||||
https://www.cgtn.com
|
||||
https://www.scmp.com
|
||||
|
||||
# India
|
||||
https://www.ndtv.com
|
||||
https://timesofindia.indiatimes.com
|
||||
https://indianexpress.com
|
||||
https://www.thehindu.com
|
||||
https://www.hindustantimes.com
|
||||
|
||||
# Japan
|
||||
https://www3.nhk.or.jp/nhkworld
|
||||
https://www.japantimes.co.jp
|
||||
https://www.asahi.com/ajw
|
||||
https://mainichi.jp/english
|
||||
https://english.kyodonews.net
|
||||
|
||||
# South Korea
|
||||
https://en.yna.co.kr
|
||||
https://www.koreaherald.com
|
||||
https://koreajoongangdaily.joins.com
|
||||
https://www.donga.com/en
|
||||
https://english.chosun.com
|
||||
|
||||
# --- AFRICA ---
|
||||
# South Africa
|
||||
https://www.news24.com
|
||||
https://www.iol.co.za
|
||||
https://www.dailymaverick.co.za
|
||||
https://www.sabcnews.com
|
||||
https://www.timeslive.co.za
|
||||
|
||||
# Nigeria
|
||||
https://www.vanguardngr.com
|
||||
https://punchng.com
|
||||
https://dailypost.ng
|
||||
https://saharareporters.com
|
||||
https://thenationonlineng.net
|
||||
|
||||
# --- MIDDLE EAST ---
|
||||
# General Region
|
||||
https://www.aljazeera.com
|
||||
https://english.alarabiya.net
|
||||
https://www.timesofisrael.com
|
||||
https://www.tehrantimes.com
|
||||
https://www.middleeasteye.net
|
||||
|
||||
# --- OCEANIA ---
|
||||
# Australia
|
||||
https://www.abc.net.au/news
|
||||
https://www.news.com.au
|
||||
https://www.9news.com.au
|
||||
https://www.smh.com.au
|
||||
https://www.theage.com.au
|
||||
# --- USA: MAJOR CITIES & LOCAL ---
|
||||
https://www.latimes.com
|
||||
https://www.chicagotribune.com
|
||||
https://www.sfchronicle.com
|
||||
https://www.bostonglobe.com
|
||||
https://www.seattletimes.com
|
||||
https://www.houstonchronicle.com
|
||||
https://www.inquirer.com
|
||||
https://www.denverpost.com
|
||||
https://www.miamiherald.com
|
||||
https://www.dallasnews.com
|
||||
https://www.startribune.com
|
||||
https://www.detroitnews.com
|
||||
https://www.ajc.com
|
||||
https://www.nydailynews.com
|
||||
https://nypost.com
|
||||
https://www.mercurynews.com
|
||||
https://www.baltimoresun.com
|
||||
https://www.oregonlive.com
|
||||
https://www.cleveland.com
|
||||
https://www.tampabay.com
|
||||
|
||||
# --- EUROPE: LOCAL & INDEPENDENT ---
|
||||
https://www.manchestereveningnews.co.uk
|
||||
https://www.scotsman.com
|
||||
https://www.belfasttelegraph.co.uk
|
||||
https://www.irishtimes.com
|
||||
https://www.berliner-zeitung.de
|
||||
https://www.leparisien.fr
|
||||
https://www.corriere.it
|
||||
https://www.elperiodico.com
|
||||
https://kyivindependent.com
|
||||
https://www.pravda.com.ua/en
|
||||
https://balkaninsight.com
|
||||
https://www.ekathimerini.com
|
||||
https://www.swissinfo.ch
|
||||
https://www.thelocal.se
|
||||
https://www.thelocal.fr
|
||||
https://www.thelocal.de
|
||||
https://www.novinite.com
|
||||
https://www.romania-insider.com
|
||||
https://hungarytoday.hu
|
||||
https://polandin.com
|
||||
|
||||
# --- MIDDLE EAST & CONFLICT ZONES ---
|
||||
https://www.haaretz.com
|
||||
https://www.jpost.com
|
||||
https://www.timesofisrael.com
|
||||
https://www.rudaw.net/english
|
||||
https://www.kurdistan24.net/en
|
||||
https://www.middleeasteye.net
|
||||
https://www.al-monitor.com
|
||||
https://www.dailysabah.com
|
||||
https://www.duvarenglish.com
|
||||
https://english.aawsat.com
|
||||
https://www.arabnews.com
|
||||
https://www.thenationalnews.com
|
||||
https://www.jordantimes.com
|
||||
https://www.naharnet.com
|
||||
https://www.tehrantimes.com
|
||||
|
||||
# --- ASIA: HOTSPOTS & LOCAL ---
|
||||
https://www.taipeitimes.com
|
||||
https://focustaiwan.tw
|
||||
https://hongkongfp.com
|
||||
https://www.bangkokpost.com
|
||||
https://www.thejakartapost.com
|
||||
https://www.straitstimes.com
|
||||
https://www.khmertimeskh.com
|
||||
https://www.irrawaddy.com
|
||||
https://www.myanmarnow.org/en
|
||||
https://www.rappler.com
|
||||
https://www.philstar.com
|
||||
https://english.hani.co.kr
|
||||
https://www.japantoday.com
|
||||
https://www.caixinglobal.com
|
||||
https://thediplomat.com
|
||||
|
||||
# --- LATIN AMERICA & AFRICA: LOCAL ---
|
||||
https://buenosairesherald.com
|
||||
https://riotimesonline.com
|
||||
https://mercopress.com
|
||||
https://www.elmostrador.cl
|
||||
https://www.jornada.com.mx
|
||||
https://www.theeastafrican.co.ke
|
||||
https://allafrica.com
|
||||
https://www.premiumtimesng.com
|
||||
https://www.dailytrust.com
|
||||
https://www.newtimes.co.rw
|
||||
https://www.herald.co.zw
|
||||
https://www.namibian.com.na
|
||||
https://www.graphic.com.gh
|
||||
https://www.thecitizen.co.tz
|
||||
https://www.monitor.co.ug
|
||||
|
||||
# --- ALTERNATIVE, INVESTIGATIVE & "FRINGE" ---
|
||||
https://theintercept.com
|
||||
https://www.propublica.org
|
||||
https://www.democracynow.org
|
||||
https://reason.com
|
||||
https://www.motherjones.com
|
||||
https://www.vox.com
|
||||
https://slate.com
|
||||
https://www.axios.com
|
||||
https://www.politico.com
|
||||
https://www.vice.com
|
||||
https://www.bellingcat.com
|
||||
https://www.project-syndicate.org
|
||||
https://cryptonews.com
|
||||
https://www.coindesk.com
|
||||
https://techcrunch.com
|
||||
Loading…
Reference in a new issue