""" Whole-site crawler for www.sueddeutsche.de (Süddeutsche Zeitung). This is the exact script that produced the Hugging Face dataset https://huggingface.co/datasets/SinclairSchneider/sueddeutsche_de — see that dataset card for a step-by-step description of the pipeline. Overview -------- * 32 worker processes share the URL frontier; a URL is routed to a worker by ``int(md5(url).hexdigest(), 16) % 32`` so that no locking is required. * The crawl is seeded with one article URL and discovers everything else by following links below ``https://www.sueddeutsche.de/``. * ``get_content()`` turns an article page into a record; pages with an empty body are dropped. Each surviving article is written to ``pages/.json``. * Known and visited URLs are appended to ``data/thread__pages*.txt``, so an interrupted crawl resumes where it left off. Create a file named ``killall.txt`` in the working directory to stop all workers cleanly. Usage ----- pip install mechanicalsoup beautifulsoup4 lxml python-dateutil fake-useragent python crawler.py Configuration ------------- Copy ``.env.example`` to ``.env`` and uncomment what you need - proxies, worker count, timeout, retries and the seed URL are all read from there (environment variables still win over the file). For a large proxy farm put one proxy per line into a text file and point ``SCRAPER_PROXY_FILE`` at it; see ``proxies.example.txt``. The private proxy addresses used in the original crawl have been removed from this published copy. Please crawl responsibly: honour robots.txt and the site's terms of use, and lower the worker count unless you have the operator's permission. """ import hashlib import multiprocessing import mechanicalsoup from bs4 import BeautifulSoup import re import json import os import io import time from dateutil.parser import parse base_url = "https://www.sueddeutsche.de/" # --- Configuration --------------------------------------------------------- # Every setting below can be supplied through the environment or through a # ".env" file placed next to this script. Copy ".env.example" to ".env" and # uncomment what you need: # # cp .env.example .env # # Nothing has to be set - the defaults are exactly the values that were used # for the original crawl. def _load_dotenv(path=".env"): """Read a ".env" file: KEY=VALUE per line, "#" starts a comment. Variables that are already set in the real environment win, so a single run can still be overridden with e.g. ``SCRAPER_THREADS=4 python crawler.py``. """ if not os.path.isfile(path): return with io.open(path, "r", encoding="utf-8") as handle: for line in handle: line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, _, value = line.partition("=") key = key.strip() value = value.strip().strip('"').strip("'") if key and key not in os.environ: os.environ[key] = value _load_dotenv() def _load_proxy_pool(): """Build the proxy pool from SCRAPER_PROXIES and/or SCRAPER_PROXY_FILE. SCRAPER_PROXIES inline list; entries separated by commas, semicolons, spaces or newlines. SCRAPER_PROXY_FILE path to a file holding one proxy per line, with blank lines and "#" comments allowed. This is the practical form for a whole proxy farm: the pool can be swapped or regenerated without touching the script or the .env. Both may be combined. Entries may be written with or without a scheme ("http://" is assumed when none is given). Duplicates are dropped and an empty pool simply means "connect directly". """ raw = os.environ.get("SCRAPER_PROXIES", "") proxy_file = os.environ.get("SCRAPER_PROXY_FILE", "").strip() if proxy_file: if not os.path.isfile(proxy_file): raise SystemExit("SCRAPER_PROXY_FILE points to a missing file: " + proxy_file) with io.open(proxy_file, "r", encoding="utf-8") as handle: raw = raw + "\n" + handle.read() cleaned = [] for line in raw.splitlines(): line = line.split("#", 1)[0].strip() if line: cleaned.append(line) pool = [] for entry in re.split(r"[,;\s]+", " ".join(cleaned)): entry = entry.strip() if not entry: continue if "://" not in entry: entry = "http://" + entry if entry not in pool: pool.append(entry) return pool PROXY_POOL = _load_proxy_pool() NUM_THREADS = int(os.environ.get("SCRAPER_THREADS", "32")) REQUEST_TIMEOUT = float(os.environ.get("SCRAPER_TIMEOUT", "10.0")) MAX_RETRIES = int(os.environ.get("SCRAPER_RETRIES", "1000")) START_URL = os.environ.get("SCRAPER_START_URL", "https://www.sueddeutsche.de/politik/italien-opposition-meloni-volksabstimmungen-li.3265512") def log(number, url): if not os.path.isdir("log"): os.mkdir("log") with open("log"+os.sep+"thread_"+str(number)+".txt", "w") as f: f.write(url) def error(number, url): if not os.path.isdir("error"): os.mkdir("error") with open("error"+os.sep+"thread_"+str(number)+".txt", "w") as f: f.write(url) def get_content(url, page_str): additional_attributes = { 'author':'', 'description':'', 'keywords':'', 'category':'', 'about':'', 'dateCreated':'', 'datePublished':'', 'dateModified':'', 'wordCount':'', 'alternativeHeadline':'', 'url':'', } dict_return = {'content':'', 'title':'', 'additional_attributes': additional_attributes} if page_str == "": return dict_return page_bs = BeautifulSoup(page_str, "lxml") try: _ = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text) except: print("Error in JSON, skip page") return dict_return paidMarker = False if page_bs.find("div", {'data-paycategory':'paid'}) == None else True if paidMarker: return dict_return title = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('headline', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else "" content = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('articleBody', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else "" author = page_bs.find('meta', {'data-manual':'author'}).get('content', '') if page_bs.find('meta', {'data-manual':'author'}) != None else '' description = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('description', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else '' keywords = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('keywords', '').split(',') if page_bs.find("script", {'type':'application/ld+json'}) != None else '' category = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('articleSection', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else "" about = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('about', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else '' dateCreated = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('dateCreated', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else '' datePublished = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('datePublished', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else '' dateModified = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('dateModified', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else '' wordCount = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('wordCount', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else '' alternativeHeadline = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('alternativeHeadline', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else '' additional_attributes = { 'author':author, 'description':description, 'keywords':keywords, 'category':category, 'about':about, 'dateCreated':dateCreated, 'datePublished':datePublished, 'dateModified':dateModified, 'wordCount':wordCount, 'alternativeHeadline':alternativeHeadline, 'url':url, } dict_return = {'content':content, 'title':title, 'additional_attributes': additional_attributes} return dict_return def get_urls(page_str): return_urls = set() page_bs = BeautifulSoup(page_str, "lxml") for tag in page_bs.findAll("a", href=True): url = tag.get("href", '') if "#" in url: continue if url.startswith(base_url): return_urls.add(url) if url.startswith("/"): url = base_url + url return_urls.add(url) return return_urls def readSavedData(iId, sPageset, sPagesetVisited): if not os.path.isdir("data"): os.mkdir("data") if os.path.isfile("data/thread_"+str(iId)+"_pages.txt"): with io.open("data/thread_"+str(iId)+"_pages.txt", "r", encoding="utf-8") as f: for line in f: if "#" in line: continue line = line.replace("\n", "") if line != "": sPageset.add(line) if os.path.isfile("data/thread_"+str(iId)+"_pages_visited.txt"): with io.open("data/thread_"+str(iId)+"_pages_visited.txt", "r", encoding="utf-8") as f: for line in f: if "#" in line: continue line = line.replace("\n", "") if line != "": sPagesetVisited.add(line) def addStartChannel(sPage, iNumberOfThreads, lQueues): iIndex = int(hashlib.md5(sPage.encode("utf")).hexdigest(),16)%iNumberOfThreads lQueues[iIndex].put(sPage) def getNextPage(lQueues, iId, sPageset, sPagesetVisited): while True: if os.path.isfile("killall.txt"): return None while not lQueues[iId].empty(): sPage = lQueues[iId].get() iLenBefore = len(sPageset) sPageset.add(sPage) iLenAfter = len(sPageset) if iLenBefore != iLenAfter: with io.open("data/thread_"+str(iId)+"_pages.txt", "a", encoding="utf-8") as f: if sPage != "" and sPage != "\t": f.write(sPage + "\n") sPagesetToVisit = sPageset - sPagesetVisited if len(sPagesetToVisit) != 0: sPage = list(sPagesetToVisit)[0] return sPage else: print("Thread " + str(iId) + " is waiting") time.sleep(3) def addPagesToVisit(sPages, iNumberOfThreads, lQueues): for sPage in sPages: if sPage != "": iIndex = int(hashlib.md5(sPage.encode("utf")).hexdigest(), 16) % iNumberOfThreads lQueues[iIndex].put(sPage) def addVisitedPages(sPage, sPagesetsetVisited, iId): iLenBefore = len(sPagesetsetVisited) sPagesetsetVisited.add(sPage) iLenAfter = len(sPagesetsetVisited) if iLenBefore != iLenAfter: with io.open("data/thread_"+str(iId)+"_pages_visited.txt", "a", encoding="utf-8") as f: if sPage != "": f.write(sPage+"\n") def crawler(iId, iNumberOfThreads, lQueues): sPageset = set() sPagesetVisited = set() readSavedData(iId, sPageset, sPagesetVisited) while True: sPage = getNextPage(lQueues, iId, sPageset, sPagesetVisited) if sPage is None: break if "#" in sPage: continue if (not "/files/" in sPage) and \ (not "/video/" in sPage) and \ (not ".jpg" in sPage) and \ (not ".pdf" in sPage) and \ len(sPage.split('/')) > 4 and \ (not ".epub" in sPage): log(iId, sPage) for i in range(MAX_RETRIES): try: lproxies = PROXY_POOL proxy = lproxies[int(int(time.time())/60)%len(lproxies)] if lproxies else None proxies = {'https': proxy, 'http': proxy} if proxy else {} browser = mechanicalsoup.StatefulBrowser() browser.session.proxies = proxies browser.open(sPage, timeout=REQUEST_TIMEOUT) page = browser.get_current_page() page_str = str(page) break except: print(sPage) print("retry") browser.close() continue browser.close() else: page_str = "" try: content = get_content(sPage, page_str) except: error(iId, sPage) if content['content'] != '': file_path = sPage.replace(base_url+"/", "").replace("/", "_")[-200:] file_path = "pages/"+file_path file_path = file_path[:-1] if file_path.endswith("_") else file_path file_path = file_path+".json" content_json = json.dumps(content) with open(file_path, "w", encoding = "utf-8") as f: f.write(content_json) else: pass sPages = get_urls(page_str) addPagesToVisit(sPages, iNumberOfThreads, lQueues) addVisitedPages(sPage, sPagesetVisited, iId) print("Thread: " + str(iId) + " chanels visited: " + str(len(sPagesetVisited)) + " channels to visit: " + str(len(sPageset - sPagesetVisited))) def main(): if not os.path.isdir("pages"): os.mkdir("pages") iNumberOfThreads = NUM_THREADS lQueues = [] mgr = multiprocessing.Manager() for i in range(iNumberOfThreads): qQueue = mgr.Queue() lQueues.append(qQueue) lIds = range(0, iNumberOfThreads) lNumberOfThreads = [iNumberOfThreads] * iNumberOfThreads llQueues = [lQueues] * iNumberOfThreads addStartChannel(START_URL, iNumberOfThreads, lQueues) lArguments = list(zip(lIds, lNumberOfThreads, llQueues)) with multiprocessing.Pool(processes=iNumberOfThreads) as pool: pool.starmap(crawler, lArguments) if __name__ == "__main__": main()