Datasets:
Download scraping/crawler.py from SinclairSchneider/achgut_de: direct link, hf CLI and curl.
- Browser
- Download file 17.1 kB
-
https://huggingface.co/datasets/SinclairSchneider/achgut_de/resolve/main/scraping/crawler.py
- Command line
-
hf download hf://datasets/SinclairSchneider/achgut_de/scraping/crawler.py
-
curl -L -o crawler.py https://huggingface.co/datasets/SinclairSchneider/achgut_de/resolve/main/scraping/crawler.py
17.1 kB
| """ | |
| Whole-site crawler for www.achgut.com (Achse des Guten). | |
| This is the exact script that produced the Hugging Face dataset | |
| https://huggingface.co/datasets/SinclairSchneider/achgut_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.achgut.com/``. | |
| * ``get_content()`` turns an article page into a record; pages with an empty | |
| body are dropped. Each surviving article is written to | |
| ``pages/<flattened-url>.json``. | |
| * Known and visited URLs are appended to ``data/thread_<id>_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 free-proxy | |
| 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 datetime import datetime | |
| from fake_useragent import UserAgent | |
| import random | |
| from dateutil.parser import parse | |
| from fp.fp import FreeProxy | |
| proxy = FreeProxy(country_id=['DE'], rand=True).get() | |
| proxies = {"http": proxy, "https": proxy} | |
| base_url = "https://www.achgut.com/" | |
| # --- 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.achgut.com/artikel/ukraine_krieg_weder_wendepunkt_noch_waffenstillstand") | |
| 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 raw(number, url, page_str): | |
| if not os.path.isdir("raw"): | |
| os.mkdir("raw") | |
| with open("raw"+os.sep+"thread_"+str(number)+".txt", "w") as f: | |
| f.write(url) | |
| f.write(page_str) | |
| def get_content(url, page_str): | |
| additional_attributes = { | |
| 'author':'', | |
| 'description':'', | |
| 'keywords':'', | |
| 'category':'', | |
| 'datePublished':'', | |
| 'url':'', | |
| } | |
| dict_return = {'content':'', 'title':'', 'additional_attributes': additional_attributes} | |
| if page_str == "": | |
| return dict_return | |
| page_bs = BeautifulSoup(page_str, "lxml") | |
| title = page_bs.find("div", {'id':'article_maincontent'}).find("h2").text if page_bs.find("div", {'id':'article_maincontent'}) != None else "" | |
| content = " ".join([x.text for x in page_bs.find("div", {'id':'article_maincontent'}).find_all("p")]) if page_bs.find("div", {'id':'article_maincontent'}) != None else "" | |
| author = page_bs.find("div", {'id':'author_header'}).text if page_bs.find("div", {'id':'author_header'}) != None else "" | |
| description = page_bs.find("meta", {'name':'description'}).get('content', '') if page_bs.find("meta", {'name':'description'}) != None else "" | |
| keywords = [x for x in page_bs.find("meta", {'name':'keywords'}).get('content', '').split(",") if x != ''] if page_bs.find("meta", {'name':'keywords'}) != None else [] | |
| category = page_bs.find("meta", {'property':'og:type'}).get('content', '') if page_bs.find("meta", {'property':'og:type'}) != None else "" | |
| datePublished = "".join([x for x in page_bs.find("div", {'class':'teaser_text_meta'}).contents if x.name == None]).replace("\t","").replace("\n", "").replace("/","").replace(" ", " ").strip() if page_bs.find("div", {'class':'teaser_text_meta'}) != None else "" | |
| additional_attributes = { | |
| 'author':author, | |
| 'description':description, | |
| 'keywords':keywords, | |
| 'category':category, | |
| 'datePublished':datePublished, | |
| '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 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: | |
| 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: | |
| 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 (not "/files/" in sPage) and \ | |
| (not "/video/" in sPage) and \ | |
| (not ".jpg" in sPage) and \ | |
| (not ".pdf" in sPage) and \ | |
| (not "#" in sPage) and \ | |
| (not "app-eu.readspeaker.com" in sPage) and \ | |
| (not ".epub" in sPage): | |
| log(iId, sPage) | |
| for i in range(MAX_RETRIES): | |
| try: | |
| lproxies = PROXY_POOL | |
| proxy = lproxies[int(int(time.time()/10))%len(lproxies)] if lproxies else None | |
| proxies = {'https': proxy, 'http': proxy} if proxy else {} | |
| browser = mechanicalsoup.StatefulBrowser() | |
| browser.session.proxies = proxies | |
| browser.set_user_agent('Mozilla/5.0') | |
| headers = { | |
| 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', | |
| 'Accept-Language': 'de-DE,de;q=0.9', | |
| 'Accept-Encoding': 'gzip, deflate, br', | |
| 'Connection': 'keep-alive', | |
| 'Upgrade-Insecure-Requests': '1', | |
| 'Sec-Fetch-Dest': 'document', | |
| 'Sec-Fetch-Mode': 'navigate', | |
| 'Sec-Fetch-Site': 'same-origin', | |
| 'Sec-Fetch-User': '?1', | |
| 'Cache-Control': 'max-age=0' | |
| } | |
| browser.session.headers.update(headers) | |
| ua = UserAgent() | |
| browser.set_user_agent(ua.random) | |
| time.sleep(random.uniform(1.0, 3.5)) | |
| browser.open(sPage, timeout=REQUEST_TIMEOUT) | |
| page = browser.get_current_page() | |
| page_str = str(page) | |
| raw(iId, sPage, page_str) | |
| if "Es ist ein Fehler aufgetreten (Fehlernummer: 1047)." in page_str: | |
| print("error, we will wait a moment and continue") | |
| time.sleep(1) | |
| continue | |
| if "You don't have permission to access this resource." in page_str: | |
| print("error 403, we will wait a moment and continue") | |
| time.sleep(10) | |
| continue | |
| break | |
| except Exception as e: | |
| print(sPage) | |
| print(f"Error: {str(e)} - Rotating proxy") | |
| print("retry") | |
| time.sleep(3) | |
| 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) | |
| addStartChannel("https://www.achgut.com/artikel/kommt_jetzt_die_musk_partei", iNumberOfThreads, lQueues) | |
| addStartChannel("https://www.achgut.com/woche", iNumberOfThreads, lQueues) | |
| addStartChannel("https://www.achgut.com/woche/P10", iNumberOfThreads, lQueues) | |
| addStartChannel("https://www.achgut.com/woche/P20", iNumberOfThreads, lQueues) | |
| addStartChannel("https://www.achgut.com/woche/P30", iNumberOfThreads, lQueues) | |
| addStartChannel("https://www.achgut.com/woche/P40", iNumberOfThreads, lQueues) | |
| addStartChannel("https://www.achgut.com/woche/P50", iNumberOfThreads, lQueues) | |
| addStartChannel("https://www.achgut.com/suche/eyJyZXN1bHRfcGFnZSI6InN1Y2hlXC9pbmRleCNzdWNoZXJnZWJuaXNzZSIsImNhdGVnb3J5IjoiNXw5fDEyfDR8MTN8NnwyNHwxNXwxOXwxNHwxOHwxNnwxN3w4fDciLCJtZW1iZXI6c2NyZWVuX25hbWUiOiJIZW5yeWsgTS4gQnJvZGVyfERpcmsgTWF4ZWlu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lcmtpc3xNYXJrdXMgVmFobGVmZWxkfEZyZWQgVmllYmFobnxSaWNoYXJkIFdhZ25lcnxCZW5qYW1pbiBXZWludGhhbHxHdW50ZXIgV2VpXHUwMGRmZ2VyYmVyfEFsZXhhbmRlciBXZW5kdHxKb2NoZW4gWmllZ2xlcnxPbGl2ZXIgWmltc2tpfEtvbGphIFp5ZGF0aXNzIn0#artikelarchiv", iNumberOfThreads, lQueues) | |
| lArguments = list(zip(lIds, lNumberOfThreads, llQueues)) | |
| with multiprocessing.Pool(processes=iNumberOfThreads) as pool: | |
| pool.starmap(crawler, lArguments) | |
| if __name__ == "__main__": | |
| main() |