Add detailed dataset card and the scraping pipeline used to build it
Browse filesFiles changed (6)
- README.md+480-15
- scraping/.env.exampleAdded+52
- scraping/README.mdAdded+83
- scraping/crawler.pyAdded+384
- scraping/finalize.ipynbAdded+203
- scraping/proxies.example.txtAdded+15
123420 unmodified lines252627282930313233343536373839404142---dataset_info:features:- name: title20 unmodified linesnum_examples: 187425download_size: 325844487dataset_size: 561544362configs:- config_name: defaultdata_files:- split: trainpath: data/train-*language:- detags:- news- newspaper- german- politicssize_categories:- 100K<n<1M---1234567891011121314151617181920212223242526272829303132333435363738394020 unmodified lines616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507---language:- depretty_name: RTL News (rtl.de)size_categories:- 100K<n<1Mtask_categories:- text-generation- text-classification- summarization- feature-extractiontags:- broadcast-news- commercial-media- entertainment- german- journalism- media- media-bias- news- news-articles- research-only- text-and-data-mining- web-scrapingannotations_creators:- no-annotationlanguage_creators:- foundmultilinguality:- monolingualsource_datasets:- originalconfigs:- config_name: defaultdata_files:- split: trainpath: data/train-*dataset_info:features:- name: title20 unmodified linesnum_examples: 187425download_size: 325844487dataset_size: 561544362---# RTL News (rtl.de)**187 425 German-language news articles** crawled from[`www.rtl.de`](https://www.rtl.de/) and published as a Hugging Face dataset.This is part of the [German Media collection](https://huggingface.co/collections/SinclairSchneider/german-media),a set of comparable corpora covering the German media landscape from public-servicebroadcasters to alternative and fringe outlets, all built with the same crawler and the sameextraction pipeline so that they can be compared and combined directly.> ## ⚠️ For scientific research only>> This corpus is published **exclusively for scientific research** under the German> research exception for text and data mining — the *Forschungsprivileg* of> **§ 60d UrhG** (implementing Art. 3 of EU Directive 2019/790). The article texts remain> the copyright of their publisher and are **not** licensed for commercial use,> redistribution, or republication. By downloading it you confirm that you use it for> non-commercial scientific research. See [Licensing and intended use](#licensing-and-intended-use).>> The articles are reproduced verbatim from the publisher's website; their content expresses> the views of that publisher, not of the dataset author.## At a glance| | ||---|---|| **Source** | [`www.rtl.de`](https://www.rtl.de/) || **Rows** | 187 425 || **Columns** | 9 (`title`, `content`, `author`, `description`, `keywords`, `category`, `datePublished`, `dateModified`, `url`) || **Language** | German (`de`) || **Split** | `train` (single split) || **Format** | Parquet, 2 shards, ≈ 311 MB download / 536 MB in memory || **Perceived partisanship** | 4.5 / 7 → *relatively neutral* ([medienkompass.org](https://medienkompass.org/deutsche-medienlandschaft/) reader survey) || **Intended use** | Scientific research only (*Forschungsprivileg*, § 60d UrhG) || **Mirror** | [`NLP-UniBW/rtl_de`](https://huggingface.co/datasets/NLP-UniBW/rtl_de) |```pythonfrom datasets import load_datasetds = load_dataset("SinclairSchneider/rtl_de", split="train")print(ds[0]["title"])```## About the source[rtl.de](https://www.rtl.de/) is the online portal of RTL Deutschland, Germany's largestcommercial broadcaster (Bertelsmann/RTL Group). The portal mixes news with a strong share of service,lifestyle, celebrity and television-related coverage, so this dataset is markedly less political incomposition than the broadsheet and public-broadcasting datasets in the same collection.## Perceived political positionThe German media compass at[medienkompass.org](https://medienkompass.org/deutsche-medienlandschaft/) places Germanmainstream and alternative outlets on two axes on the basis of a reader survey(*n* ≈ 1 154 participants in total, building on a media map by the think tank*polisphere*; the quality axis is adapted from Vanessa Otero's media chart).* **x axis — *Parteilichkeit* (partisanship), 1–7:** `< 3.5` left, `3.5 – 4.5` relativelyneutral, `> 4.5` right.`1` far-left (fake news and conspiracy theories) · `2` left mission (questionable journalisticstandards) · `3` leaning left · `4` minimal partisan tendency · `5` leaning right ·`6` right mission (questionable journalistic standards) · `7` far-right (fake news andconspiracy theories).* **y axis — *Qualität* (quality), 1–5:** `1` sensationalist / clickbait · `2` basic information ·`3` meets high standards · `4` analytical · `5` complex.In that survey, **RTL** is rated:| | Score | Reading ||---|---:|---|| Partisanship (1–7) | **4.5** | relatively neutral || Quality (1–5) | **1.5** | on the 1 = clickbait … 5 = complex scale |```Parteilichkeit (partisanship): 1 = far left ... 7 = far right1 2 3 4 5 6 7|---------|---------|---------|---------|---------|---------|^RTL = 4.5left <--------------| neutral |--------------> right3.5 4.5```For context, here is the full survey table, sorted from left to right — the other outlets inthe collection are directly comparable:| Outlet | Partisanship (1–7) | Quality (1–5) ||---|---:|---:|| indymedia | 2.0 | 1.7 || Jungle World | 2.3 | 2.3 || junge Welt | 2.4 | 2.3 || neues Deutschland | 2.6 | 2.3 || der Freitag | 2.7 | 2.9 || die Tageszeitung | 2.8 | 2.7 || Vice | 2.8 | 1.8 || NachDenkSeiten | 3.1 | 3.0 || Frankfurter Rundschau | 3.4 | 2.8 || SPON | 3.5 | 2.1 || Spiegel Print | 3.5 | 2.9 || Süddeutsche | 3.5 | 3.3 || WDR | 3.5 | 2.8 || Tagesspiegel | 3.6 | 2.8 || Zeit | 3.6 | 3.5 || ARD | 3.7 | 2.9 || NDR | 3.7 | 2.8 || Deutschlandfunk | 3.8 | 3.5 || Stern | 3.8 | 2.1 || ZDF | 3.8 | 2.8 || MDR | 4.1 | 2.5 || Handelsblatt | 4.3 | 3.3 || NTV | 4.3 | 2.1 || BR | 4.4 | 2.6 || N24 | 4.4 | 2.0 || Wirtschaftswoche | 4.4 | 3.1 || Frankfurter Allgemeine | 4.5 | 3.3 || **RTL** ⬅ this dataset | **4.5** | **1.5** || Die Welt | 4.8 | 2.5 || Cicero | 4.9 | 3.1 || Focus Online | 4.9 | 1.7 || Deutsche Wirtschafts Nachrichten | 5.0 | 2.2 || MM News | 5.1 | 1.7 || RT Deutsch | 5.1 | 2.0 || Achgut | 5.2 | 2.4 || BILD | 5.2 | 1.3 || Tichys | 5.5 | 2.6 || junge Freiheit | 5.8 | 1.9 || Compact | 6.0 | 1.8 |> **How to read these numbers.** They are *perception* data from a self-selected online survey,> not a content analysis: participants rated outlets they know, the sample is not> representative of the German population, and the site itself describes the project as an early> iteration. Treat them as a rough, crowd-sourced orientation — useful for grouping datasets into> coarse political blocks, not as ground truth for bias labelling.## Dataset structureSingle `train` split with 187 425 rows and the following columns:| Column | Type | Description | Extracted from ||---|---|---|---|| `title` | `string` | Headline of the article. | `headline` from the `ld+json` block containing `headline` || `content` | `string` | Full plain-text body of the article. | `articleBody` from the `ld+json` block containing `articleBody` || `author` | `string` | Author(s) as published by the outlet. | `author` from `ld+json` — when it is a list, the **last** entry's `name` is used || `description` | `string` | Teaser / meta description of the article. | `description` from `ld+json` || `keywords` | `list[string]` | Topic keywords / tags assigned by the publisher. | `<meta name="keywords">`, split on `,` and stripped || `category` | `string` | Section the article was published in. | `a.Breadcrumb_link__VP_Re` entries whose `href` has more than two path segments (reverse-sorted, first) || `datePublished` | `string` | Publication timestamp. | `datePublished` from `ld+json` || `dateModified` | `string` | Timestamp of the last editorial update. | `dateModified` from `ld+json` || `url` | `string` | Canonical URL the article was fetched from. | the crawled URL |### Example record```json{"title": "Scheinfasten: Leichter Abnehmen durch Fasten ohne Hungern","content": "Ihr wollt schnell ein paar Pfunde loswerden, habt aber keine Lust auf Verzicht?\nDann könnte Scheinfasten genau das Richtige für euch sein. Durch die Wahl der richtigen Lebensmittel täuscht ihr eurem Körper einen Nahrungsmangel vor, sodass er in den Fasten-Modus schaltet. Wir verraten euch, wie euer Speiseplan dafür optimalerweise zusammengesetzt sein sollte. Was unterscheidet das Scheinfasten vom …","author": "Nora Rieder","description": "Beim Scheinfasten täuscht ihr eurem Körper durch eine spezielle Lebensmittelzusammenstellung einen Nahrungsmangel vor. Folglich schaltet er in den Fasten-Modus. Die Folge: Ihr baut Körperfett ab und die die Pfunde purzeln. ","keywords": ["Diät","Abnehmen","schnell abnehmen","gesund abnehmen","Abnehmen Tipps","Diätplan","Diät Tipps","Ernährungsplan","…"],"category": "Abnehmen","datePublished": "2025-05-20T16:13:03+02:00","dateModified": "2025-05-20T16:13:03+02:00","url": "https://www.rtl.de/ratgeber/gesundheit/abnehmen/scheinfasten-leichter-abnehmen-durch-fasten-ohne-hungern-id4370416.html"}```## Temporal coverageThe `datePublished` column could be parsed for **187 425 of 187 425** rows (100.0 %). Those rows span **2009-08-21 → 2025-06-14**.| Year | Articles | ||---:|---:|:---|| 2009 | 8 | `█` || 2010 | 30 | `█` || 2011 | 144 | `█` || 2012 | 468 | `█` || 2013 | 1 078 | `█` || 2014 | 2 482 | `██` || 2015 | 3 299 | `██` || 2016 | 7 900 | `█████` || 2017 | 2 957 | `██` || 2018 | 3 489 | `██` || 2019 | 6 971 | `█████` || 2020 | 13 913 | `██████████` || 2021 | 32 586 | `██████████████████████` || 2022 | 34 954 | `████████████████████████` || 2023 | 33 453 | `███████��███████████████` || 2024 | 31 264 | `█████████████████████` || 2025 | 12 429 | `█████████` |## How the data was collectedThe whole pipeline is contained in this repository under [`scraping/`](./scraping) and consistsof two steps: a distributed crawler that walks the site and writes one JSON file per article, anda consolidation notebook that merges those files into the dataset you are reading.### 1. Crawling — [`scraping/crawler.py`](./scraping/crawler.py)The crawler is a breadth-first whole-site crawler built on[MechanicalSoup](https://mechanicalsoup.readthedocs.io/) and `multiprocessing`:1. **Sharded frontier.** 32 worker processes each own one `multiprocessing.Manager().Queue()`.A URL is assigned to a worker by `int(md5(url).hexdigest(), 16) % 32`, so every URL is alwayshandled by the same worker and no locking or cross-process deduplication is needed.2. **Seed.** The crawl is seeded with a single article URL(`https://www.rtl.de/news/flugzeugabsturz-in-indien-studentin-verpasst-todesflieger-um-zehn-minuten-id4415181.html`) and discoverseverything else by following links.3. **Link discovery.** Every fetched page is parsed with BeautifulSoup/lxml; all `<a href>` valuesthat start with `https://www.rtl.de/` or with `/` (which are then made absolute) are added to thefrontier. URLs containing `#` are dropped.4. **URL filtering.** Before fetching, a URL is skipped when it contains `/files/`, `/video/`,`.jpg`, `.pdf`, `.xml`, `.pptx`, `.shtml` or `.epub`, when it contains `/api/`, or when it has fewer than five path segments (which filters out section index pages).5. **Fetching.** Each URL gets up to 10 attempts with a 10 s timeout.6. **Extraction.** `get_content()` turns the HTML into a record (see below). Only pages with anon-empty `content` are written out, as `pages/<flattened-url>.json`.7. **Resumability.** Each worker appends every known and every visited URL to`data/thread_<id>_pages.txt` and `data/thread_<id>_pages_visited.txt`, and re-reads them onstart, so an interrupted crawl continues where it stopped. Creating a file named `killall.txt`in the working directory stops all workers cleanly.Crawler settings used for this site:- **Worker processes:** 32 (`iNumberOfThreads = 32`)- **Retries per URL:** 10, with a 10-second socket timeout per attempt- **Proxy pool:** not used — the original crawl connected directly (the published script can still route through proxies via `SCRAPER_PROXIES`, see below)- **User-agent rotation:** yes, a random UA per request via `fake_useragent`- **Politeness delay:** `time.sleep(random.uniform(1.0, 3.5))` before every request- **Bot-challenge handling:** responses containing `#challenge-error-text` or `You don't have permission to access` are discarded and retried after a short pause- **Raw HTML dump:** enabled (`raw/`), used for debugging the parser- **Site-specific:** `/api/` URLs excluded**Paywall handling.** The site serves its articles without a paywall, so no paywall filter was necessary.### 2. Article extraction`get_content()` reads the fields from the page's JSON-LD (`<script type="application/ld+json">`)and/or its HTML, as follows:| Field | Source in the page ||---|---|| `title` | `headline` from the `ld+json` block containing `headline` || `content` | `articleBody` from the `ld+json` block containing `articleBody` || `author` | `author` from `ld+json` — when it is a list, the **last** entry's `name` is used || `description` | `description` from `ld+json` || `keywords` | `<meta name="keywords">`, split on `,` and stripped || `category` | `a.Breadcrumb_link__VP_Re` entries whose `href` has more than two path segments (reverse-sorted, first) || `datePublished` | `datePublished` from `ld+json` || `dateModified` | `dateModified` from `ld+json` || `url` | the crawled URL |Each field is read from whichever `ld+json` block actually contains the correspondingkey, because `rtl.de` emits several blocks per page. Pages without any `ld+json`, or with a block that doesnot parse, are skipped. The crawler additionally excludes `/api/` URLs from the frontier.Each article is stored as a JSON file of the shape```json{"title": "…","content": "…","additional_attributes": { "author": "…", "description": "…", "keywords": "…", "category": "…", "datePublished": "…", "dateModified": "…", "url": "…" }}```### 3. Consolidation — [`scraping/finalize.ipynb`](./scraping/finalize.ipynb)1. `glob("pages/*.json")` collects every article file.2. The nested records are flattened into one `pandas.DataFrame` column per field.3. `df.drop_duplicates(subset=['title'])` removes duplicates — the same article is often reachableunder several URLs (print/mobile variants, tracking parameters, section mirrors), and theheadline is the most reliable identity key available.4. The frame is written to `rtl_de.json` and pushed with`datasets.Dataset.from_pandas(df).push_to_hub("SinclairSchneider/rtl_de")`.### Reproducing the crawl```bashpip install mechanicalsoup beautifulsoup4 lxml python-dateutil fake-useragent \pandas datasets huggingface_hub tqdmmkdir rtl_de && cd rtl_decurl -L -O https://huggingface.co/datasets/SinclairSchneider/rtl_de/resolve/main/scraping/crawler.pypython crawler.py # writes pages/*.json; `touch killall.txt` to stopjupyter notebook finalize.ipynb```#### Routing the crawl through your own proxiesThe original crawl ran behind a pool of forward proxies on a private network. Those addresses areinfrastructure-specific and have been **removed** from the published script. Instead, `crawler.py`reads the `SCRAPER_PROXIES` environment variable: a comma-separated list of proxies, written withor without a scheme (`http://` is assumed when none is given). One entry is picked per request, soa pool spreads the load across several exits.```bash# a single proxyexport SCRAPER_PROXIES="proxy-a.example.com:3128"# a pool, rotated per requestexport SCRAPER_PROXIES="proxy-a.example.com:3128,proxy-b.example.com:3128"# with an explicit scheme and credentialsexport SCRAPER_PROXIES="http://user:pass@proxy.example.com:3128"# SOCKS, if PySocks is installedexport SCRAPER_PROXIES="socks5://localhost:9050"# back to a direct connection — this is the defaultunset SCRAPER_PROXIESpython crawler.py```Internally this becomes `requests`' standard `{'http': …, 'https': …}` proxy mapping; with thevariable unset the mapping is empty and the crawler connects directly. No credentials, cookies orpersonal data are contained in the published code.**Please crawl responsibly:** respect `robots.txt` and the site's terms of use, keep theconcurrency far below the 32 workers used here unless you have the site's permission, and preferthis published dataset over re-crawling.## Usage```pythonfrom datasets import load_datasetimport pandas as pdds = load_dataset("SinclairSchneider/rtl_de", split="train")# stream instead of downloading everythingstream = load_dataset("SinclairSchneider/rtl_de", split="train", streaming=True)print(next(iter(stream))["title"])# as a DataFramedf = ds.to_pandas()df["datePublished"] = pd.to_datetime(df["datePublished"], errors="coerce", utc=True, format="mixed")recent = df[df["datePublished"].dt.year >= 2024]print(len(recent), "articles from 2024 onwards")```Combining several outlets into one comparative corpus:```pythonfrom datasets import load_dataset, concatenate_datasetsoutlets = ["SinclairSchneider/rtl_de", "SinclairSchneider/tagesschau_de"]parts = []for name in outlets:d = load_dataset(name, split="train").select_columns(["title", "content", "url"])parts.append(d.add_column("outlet", [name.split("/")[-1]] * len(d)))corpus = concatenate_datasets(parts)```## Limitations and biases- **Crawl, not archive.** Coverage is whatever was reachable by following links from the seed URLat crawl time. Articles that were deleted, depublished or orphaned before the crawl are missing,and old content is covered less densely than recent content.- **Free content only.** All articles on this site are freely accessible, so no paywall bias applies — but non-article page types (galleries, video pages, live tickers) are mostly absent because they have no extractable body text.- **Deduplication by headline.** Two genuinely different articles with an identical headline(common for recurring formats such as weather or daily briefings) collapse into one row.- **Noisy metadata.** `author`, `category` and `keywords` come straight from the publisher's markup,which changed over the years; empty strings are common and category labels are not harmonisedacross outlets.- **Editorial perspective.** This is the output of a single outlet. Any model trained on it aloneinherits that outlet's selection of topics, framing and vocabulary — which is exactly why thecollection provides the same pipeline across the political spectrum.- **No text normalisation.** Bodies are the concatenated paragraphs as published, includingtypographic quotes, soft hyphens and occasional residual boilerplate.## Licensing and intended use### Scientific research only — *Forschungsprivileg* (§ 60d UrhG)This dataset is made available **solely for the purpose of scientific research**. The legal basisis the German text-and-data-mining exception for research, the so-called **Forschungsprivileg**:- **§ 60d UrhG** — *Text und Data Mining für Zwecke der wissenschaftlichen Forschung* — allowsresearch organisations to make reproductions of lawfully accessible works in order to carry outtext and data mining for **non-commercial** scientific research, and to share the resultingcorpus with a specifically limited circle of people for joint research and with individual thirdparties for the purpose of quality assurance.- It implements **Art. 3 of Directive (EU) 2019/790** (the DSM Directive); comparable researchexceptions exist in the other EU member states.- § 60d UrhG does **not** cover commercial exploitation. Research organisations that give acommercial enterprise preferential access are explicitly excluded from the privilege.### What this means for you✅ **Permitted** — using the corpus for non-commercial scientific research: text and data mining,corpus linguistics, media-bias and discourse analysis, training and evaluating research models,reproducing published findings, and quality checks by individual third parties.❌ **Not permitted** — commercial use or commercial model training; redistributing or republishingthe article texts; presenting the texts as your own; building products or services on the articletexts; any use that substitutes for reading the publisher's own website.The **article texts remain the copyright of RTL and its publisher.** No licence to them isgranted or implied by this repository. Only the crawling and extraction code in `scraping/` isoffered for free reuse.If your intended use falls outside the research exception, obtain permission from the rightsholder, or use only the derived, non-expressive data (statistics, embeddings, counts). Note that§ 60d UrhG also expects research corpora to be deleted once they are no longer needed for theresearch purpose, with archiving permitted at trusted institutions.If you are a rights holder and want content removed, please open a discussion on this repository.> This section is an orientation for researchers, not legal advice. Responsibility for your own> use of the data remains with you and your institution.## Citation```bibtex@misc{rtl_de_dataset,title = {RTL News (rtl.de): a corpus of German news articles},author = {Schneider, Sinclair},year = {2025},howpublished = {Hugging Face},url = {https://huggingface.co/datasets/SinclairSchneider/rtl_de}}```## See also- The full [German Media collection](https://huggingface.co/collections/SinclairSchneider/german-media)- Mirror of this dataset: [`NLP-UniBW/rtl_de`](https://huggingface.co/datasets/NLP-UniBW/rtl_de)- [medienkompass.org — Deutsche Medienlandschaft](https://medienkompass.org/deutsche-medienlandschaft/),the source of the perceived-partisanship figures above
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# ---------------------------------------------------------------------------# crawler.py configuration for www.rtl.de## Copy this file to `.env` and uncomment the lines you need:## cp .env.example .env## Variables that are already set in the real environment take precedence over# this file, so a single run can still be overridden on the command line:## SCRAPER_THREADS=4 python crawler.py## Everything here is optional - the defaults shown are exactly the values that# were used for the original crawl.# ---------------------------------------------------------------------------
# === Proxies ===============================================================
# Inline pool. Separate entries with commas, semicolons, spaces or newlines.# A scheme is optional - "http://" is assumed when none is given. One entry is# picked per request, so several entries spread the load over several exits.#SCRAPER_PROXIES=proxy-a.example.com:3128,proxy-b.example.com:3128
# ... with an explicit scheme and credentials:#SCRAPER_PROXIES=http://user:pass@proxy.example.com:3128
# ... SOCKS (requires PySocks):#SCRAPER_PROXIES=socks5://localhost:9050
# For a whole proxy farm, keep the list in its own file instead: one proxy per# line, blank lines and "#" comments allowed. See `proxies.example.txt`.# This scales to thousands of entries and can be regenerated by another tool# without ever touching this file. Both settings may be combined.#SCRAPER_PROXY_FILE=proxies.txt
# Leave both unset to crawl over a direct connection - that is the default.
# === Crawler tuning ========================================================
# Number of worker processes sharing the URL frontier.#SCRAPER_THREADS=32
# Socket timeout per request, in seconds.#SCRAPER_TIMEOUT=10.0
# Attempts per URL before it is given up on.#SCRAPER_RETRIES=10
# Seed URL the crawl starts from. Any article URL on the site works.#SCRAPER_START_URL=https://www.rtl.de/news/flugzeugabsturz-in-indien-studentin-verpasst-todesflieger-um-zehn-minuten-id4415181.html1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283# How this dataset was built
| File | Purpose ||---|---|| [`crawler.py`](./crawler.py) | Distributed whole-site crawler for `www.rtl.de`. Writes one JSON file per article to `pages/`. || [`finalize.ipynb`](./finalize.ipynb) | Merges `pages/*.json` into a single table, deduplicates it and pushes it to the Hub. || [`.env.example`](./.env.example) | Configuration template. Copy to `.env` and uncomment what you need. || [`proxies.example.txt`](./proxies.example.txt) | Proxy-list template for `SCRAPER_PROXY_FILE` — one proxy per line. |
```bashpip install mechanicalsoup beautifulsoup4 lxml python-dateutil fake-useragent \ pandas datasets huggingface_hub tqdm
python crawler.py # writes pages/*.json; `touch killall.txt` to stopjupyter notebook finalize.ipynb```
## Configuration
All settings are optional and are read from the environment or from a `.env`file next to `crawler.py`. The defaults are exactly the values used for theoriginal crawl.
```bashcp .env.example .env # then uncomment what you need```
| Variable | Meaning ||---|---|| `SCRAPER_PROXIES` | Inline proxy pool — entries separated by commas, semicolons, spaces or newlines. || `SCRAPER_PROXY_FILE` | Path to a file with **one proxy per line** — the practical form for a proxy farm. || `SCRAPER_THREADS` | Number of worker processes sharing the URL frontier. || `SCRAPER_TIMEOUT` | Socket timeout per request, in seconds. || `SCRAPER_RETRIES` | Attempts per URL before giving up. || `SCRAPER_START_URL` | Seed URL the crawl starts from. |
Environment variables take precedence over `.env`, so a single run can beoverridden on the command line:
```bashSCRAPER_THREADS=4 python crawler.py```
### Proxies
The original crawl ran behind a pool of forward proxies on a private network.Those addresses have been removed from this published copy. A scheme isoptional on every entry (`http://` is assumed); one entry is picked perrequest, so a pool spreads the load over several exits.
```bash# a single proxyexport SCRAPER_PROXIES="proxy-a.example.com:3128"
# a small pool, rotated per requestexport SCRAPER_PROXIES="proxy-a.example.com:3128,proxy-b.example.com:3128"
# with an explicit scheme and credentialsexport SCRAPER_PROXIES="http://user:pass@proxy.example.com:3128"
# SOCKS, if PySocks is installedexport SCRAPER_PROXIES="socks5://localhost:9050"```
For a **whole proxy farm**, keep the list in its own file — one proxy per line,blank lines and `#` comments allowed — and point `SCRAPER_PROXY_FILE` at it.The file can hold thousands of entries and be regenerated by another toolwithout touching `.env` or the script:
```bashcp proxies.example.txt proxies.txt # then fill in your own entriesecho 'SCRAPER_PROXY_FILE=proxies.txt' >> .envpython crawler.py```
Leave both unset to crawl over a direct connection — that is the default andwhat most of the crawls in this collection used.
The scripts contain no credentials, cookies or personal data.
Please crawl responsibly: honour `robots.txt` and the site's terms of use, keepconcurrency well below the 32 workers used here unless you have the operator'spermission, and prefer the published dataset over re-crawling.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384"""Whole-site crawler for www.rtl.de (RTL).
This is the exact script that produced the Hugging Face datasethttps://huggingface.co/datasets/SinclairSchneider/rtl_de — see that dataset card for astep-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.rtl.de/``.* ``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 python crawler.py
Configuration-------------Copy ``.env.example`` to ``.env`` and uncomment what you need - proxies, workercount, timeout, retries and the seed URL are all read from there (environmentvariables still win over the file). For a large proxy farm put one proxy perline into a text file and point ``SCRAPER_PROXY_FILE`` at it; see``proxies.example.txt``. The private proxy addresses used in the original crawlhave been removed from this published copy.
Please crawl responsibly: honour robots.txt and the site's terms of use, andlower the worker count unless you have the operator's permission."""
import hashlibimport multiprocessingimport mechanicalsoup
from bs4 import BeautifulSoupimport reimport jsonimport osimport ioimport timeimport randomfrom fake_useragent import UserAgent
from dateutil.parser import parse
base_url = "https://www.rtl.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", "10"))START_URL = os.environ.get("SCRAPER_START_URL", "https://www.rtl.de/news/flugzeugabsturz-in-indien-studentin-verpasst-todesflieger-um-zehn-minuten-id4415181.html")
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':'', 'dateModified':'', 'url':'', } dict_return = {'content':'', 'title':'', 'additional_attributes': additional_attributes} if page_str == "": return dict_return page_bs = BeautifulSoup(page_str, "lxml")
if page_bs.find("script", {'type':'application/ld+json'}) == None: return dict_return
try: if page_bs.find_all("script", {'type':'application/ld+json'}) != None: _ = json.loads(sorted(['{}']+[x.text for x in page_bs.find_all("script", {'type':'application/ld+json'}) if "headline" in x.text])[0]) except: print("Error in JSON, skip page") return dict_return title = json.loads(sorted(['{}']+[x.text for x in page_bs.find_all("script", {'type':'application/ld+json'}) if "headline" in x.text])[0]).get('headline', '').strip() if page_bs.find_all("script", {'type':'application/ld+json'}) != None else "" content = json.loads(sorted(['{}']+[x.text for x in page_bs.find_all("script", {'type':'application/ld+json'}) if "articleBody" in x.text])[0]).get('articleBody', '').strip() if page_bs.find_all("script", {'type':'application/ld+json'}) != None else "" if page_bs.find_all("script", {'type':'application/ld+json'}) != None: if type(json.loads(sorted(['{}']+[x.text for x in page_bs.find_all("script", {'type':'application/ld+json'}) if "author" in x.text])[0]).get('author')) == type([]): author = ([{}]+json.loads(sorted(['{}']+[x.text for x in page_bs.find_all("script", {'type':'application/ld+json'}) if "author" in x.text])[0]).get('author', [{}]))[-1].get('name', '') else: author = json.loads(sorted(['{}']+[x.text for x in page_bs.find_all("script", {'type':'application/ld+json'}) if "author" in x.text])[0]).get('author', {}).get('name', '') else: author = "" description = json.loads(sorted(['{}']+[x.text for x in page_bs.find_all("script", {'type':'application/ld+json'}) if "description" in x.text])[0]).get('description', '') if page_bs.find_all("script", {'type':'application/ld+json'}) != None else "" keywords = [x.strip() for x in page_bs.find("meta", {'name':'keywords'}).get('content', '').split(",")] if page_bs.find("meta", {'name':'keywords'}) != None else [] category = sorted(['']+[x.text for x in page_bs.find_all("a", {'class':'Breadcrumb_link__VP_Re'}) if len(x.get('href', '').split('/'))>2], reverse=True)[0] if page_bs.find("a", {'class':'Breadcrumb_link__VP_Re'}) != None else "" datePublished = json.loads(sorted(['{}']+[x.text for x in page_bs.find_all("script", {'type':'application/ld+json'}) if "datePublished" in x.text])[0]).get('datePublished', '') if page_bs.find_all("script", {'type':'application/ld+json'}) != None else "" dateModified = json.loads(sorted(['{}']+[x.text for x in page_bs.find_all("script", {'type':'application/ld+json'}) if "dateModified" in x.text])[0]).get('dateModified', '') if page_bs.find_all("script", {'type':'application/ld+json'}) != None else "" additional_attributes = { 'author':author, 'description':description, 'keywords':keywords, 'category':category, 'datePublished':datePublished, 'dateModified':dateModified, '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 "/api/" in sPage) and \ (not ".jpg" in sPage) and \ (not ".pdf" in sPage) and \ (not ".xml" in sPage) and \ (not ".pptx" in sPage) and \ (not ".shtml" 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())/1)+7)%len(lproxies)] if lproxies else None proxies = {'https': proxy, 'http': proxy} if proxy else {} browser = mechanicalsoup.StatefulBrowser() ua = UserAgent() browser.set_user_agent(ua.random) browser.session.proxies = proxies
time.sleep(random.uniform(1.0, 3.5)) browser.open(sPage, timeout=REQUEST_TIMEOUT) page = browser.get_current_page() page_str = str(page) if "#challenge-error-text" in page_str: print("error, we will wait a moment and continue") time.sleep(1) continue if "You don't have permission to access" in page_str: print("error, we will wait a moment and continue") time.sleep(1) continue raw(iId, sPage, page_str) 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# `RTL News (rtl.de)` — consolidation notebook\n", "\n", "This notebook is the second half of the pipeline behind\n", "[`SinclairSchneider/rtl_de`](https://huggingface.co/datasets/SinclairSchneider/rtl_de).\n", "\n", "`crawler.py` writes one JSON file per article into `pages/`. This notebook\n", "\n", "1. reads every `pages/*.json`,\n", "2. flattens the nested records into one `pandas` column per field,\n", "3. drops duplicate articles by headline (`drop_duplicates(subset=['title'])`),\n", "4. writes `rtl_de.json` and pushes the result to the Hugging Face Hub.\n", "\n", "Outputs have been cleared before publication.\n", "" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import glob\n", "import json\n", "import pandas as pd\n", "from datasets import Dataset\n", "import huggingface_hub\n", "from dateutil.parser import parse\n", "from tqdm import tqdm" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open(\"pages/wetter_wetter-zu-vatertag-und-sommeranfang-2025-regen-laesst-den-mai-absaufen-kommen-danach-hitze-und-blitze-id4375988.html.json\", \"r\", encoding=\"utf-8\") as f:\n", " json_input = f.read()\n", " dict_input_example = json.loads(json_input)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "dict_input_example" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "json_files = glob.glob(\"pages/*.json\")\n", "len(json_files)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "title = []\n", "content = []\n", "author = []\n", "description = []\n", "keywords = []\n", "category = []\n", "datePublished = []\n", "dateModified = []\n", "url = []\n", "for file in tqdm(json_files):\n", " with open(file, \"r\") as f:\n", " d = json.loads(f.read())\n", " title.append(d['title'])\n", " content.append(d['content'])\n", " author.append(d['additional_attributes']['author'])\n", " description.append(d['additional_attributes']['description'])\n", " keywords.append(d['additional_attributes']['keywords'])\n", " category.append(d['additional_attributes']['category'])\n", " datePublished.append(d['additional_attributes']['datePublished'])\n", " dateModified.append(d['additional_attributes']['dateModified'])\n", " url.append(d['additional_attributes']['url'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = pd.DataFrame(\n", " {\n", " 'title': title,\n", " 'content': content,\n", " 'author': author,\n", " 'description': description,\n", " 'keywords': keywords,\n", " 'category': category,\n", " 'datePublished': datePublished,\n", " 'dateModified': dateModified,\n", " 'url': url,\n", " }\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = df.drop_duplicates(subset=['title'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = df.reset_index(drop=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.to_json(\"rtl_de.json\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ds = Dataset.from_pandas(df)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ds.push_to_hub(\"SinclairSchneider/rtl_de\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ds.push_to_hub(\"NLP-UniBW/rtl_de\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415# One proxy per line. Blank lines and "#" comments are ignored.# A scheme is optional - "http://" is assumed when none is given.## Copy this file (e.g. to `proxies.txt`), fill in your own entries and point# SCRAPER_PROXY_FILE at it:## SCRAPER_PROXY_FILE=proxies.txt## This is the convenient form for a large proxy farm - the file can hold# thousands of lines and be regenerated by another tool at any time.
proxy-a.example.com:3128proxy-b.example.com:3128http://user:pass@proxy-c.example.com:3128socks5://localhost:9050README.md+480-15
scraping/.env.exampleAdded+52
scraping/README.mdAdded+83
scraping/crawler.pyAdded+384
scraping/finalize.ipynbAdded+203
scraping/proxies.example.txtAdded+15