Add detailed dataset card and the scraping pipeline used to build it
Browse filesFiles changed (6)
- README.md+127-152
- scraping/.env.example+25-12
- scraping/README.md+51-29
- scraping/crawler.py+222-115
- scraping/finalize.ipynbAdded+233
- scraping/proxies.example.txtAdded+15
12345672 unmodified lines101112131415161718192021222324252627282944 unmodified lines7475767778798081828384858629 unmodified lines1161171181191201211221231241251261271281291301311 unmodified line13313413513613713813914014114214314414514614714814915019 unmodified lines17017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020140 unmodified lines2422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762771 unmodified line2792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113124 unmodified lines31731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137223 unmodified lines3963973983994004014024 unmodified lines4074084094104114124134144154164174184194204214224234244254264274284294304311 unmodified line43343443543643743843944044144244344444544644744844945045145245345411 unmodified lines4664674684694704714724 unmodified lines477478479480481482---language:- enpretty_name: USA Today (usatoday.com)size_categories:- 100K<n<1Mtask_categories:2 unmodified lines- summarization- feature-extractiontags:- Newspaper- Politics- US- english- journalism- media- national-news- news- news-articles- research-only- sports- text-and-data-mining- united-states- us-news- web-scrapingannotations_creators:- no-annotation44 unmodified linesdataset_size: 2952892502---# USA Today (usatoday.com)**745 945 English-language news articles** crawled from[`eu.usatoday.com`](https://eu.usatoday.com/) and published as a Hugging Face dataset.This is part of the [International Newspapers collection](https://huggingface.co/collections/SinclairSchneider/international-newspapers-6900fdd5083089f336574c82), a set of news corporafrom outside Germany that complements the[German Media collection](https://huggingface.co/collections/SinclairSchneider/german-media).> ## ⚠️ For scientific research only>29 unmodified lines## About the source[USA Today](https://www.usatoday.com/) is a national daily newspaper in the UnitedStates, launched in 1982 by Gannett, which still publishes it. Its website covers national news,politics, sports, entertainment, money, tech, travel and lifestyle. The crawl started on`eu.usatoday.com`, the variant of the site served to visitors from the European Union, but followedevery link containing `usatoday.com`. It therefore also contains `www.usatoday.com` pages and thesports sub-sites hosted on `usatoday.com` subdomains (team "wire" sites, *For The Win*, *Golfweek*,*MMA Junkie* and others).Sports is by far the largest section: 46 % of the rows have the category `sports`, followed by`news` (23 %) and `entertainment` (12 %).## Dataset structure1 unmodified line| Column | Type | Description | Extracted from ||---|---|---|---|| `title` | `string` | Headline of the article. | `og:title` meta tag || `content` | `string` | Full plain-text body of the article. | all `<p>` inside `<article class="primary-content">`, space-joined || `authors` | `list[string]` | List of author names as published by the outlet. | texts of all `<a class="authors">` || `description` | `string` | Teaser / meta description of the article. | `description` from the first `ld+json` block || `keywords` | `list[string]` | Topic keywords / tags assigned by the publisher. | `<meta name="news_keywords">`, split on `,` (entries are not stripped) || `category` | `string` | Section the article was published in. | first segment of `cst` in the page's `<script type="application/json">` || `subcategory` | `string` | Sub-section or kicker below the main section. | second segment of that `cst` value || `dateCreated` | `string` | Timestamp at which the CMS record was created. | `dateCreated` from the first `ld+json` block || `datePublished` | `string` | Publication timestamp. | `datePublished` from the first `ld+json` block || `dateModified` | `string` | Timestamp of the last editorial update. | `dateModified` from the first `ld+json` block || `primaryTag` | `string` | Main topic tag assigned in the CMS. | `primaryTag.name` from the `application/json` block || `contentId` | `int64` | Publisher's numeric content / asset id. | `contentId` from the `application/json` block (Gannett's numeric asset id) || `url` | `string` | Canonical URL the article was fetched from. | the crawled URL |### Example record19 unmodified lines"U.S. Congress","Donald Trump","Government","Politics","Washington"," D.C.","Overall Negative","Legislative Branch","Campaigns & Elections","Democratic Party","Mike Johnson","Washington","U.S. Senate","U.S. House of Representatives","Republican Party","Executive Branch","Welfare & Unemployment","U.S. Department of Agriculture","Congress","Modular Story","New York"," NY","Zohran Mamdani","Hakeem Jeffries","New York","Angus King","Catherine Cortez Masto","Rand Paul","Sean Duffy"],"category": "news","subcategory": "politics",40 unmodified lines## How the data was collectedThe crawler is contained in this repository under [`scraping/`](./scraping). It walks the site andwrites one JSON file per article; a consolidation step then merges those files into the dataset youare reading.### 1. Crawling — [`scraping/crawler.py`](./scraping/crawler.py)The crawler is a breadth-first whole-site crawler built on `multiprocessing`. Unlike the German Mediacrawlers it does not download pages itself: it hands every URL to an **HTML-rendering service** andparses the page source that service returns.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://eu.usatoday.com/story/news/world/2025/10/30/donald-trump-trade-tariffs-china-xi-jinping/86974396007/`) and discovers everything else by following links.3. **Link discovery.** Every fetched page is parsed with BeautifulSoup/lxml; all `<a href>` valuesthat start with `https://eu.usatoday.com/`, or with `/` (which are then prefixed with `https://eu.usatoday.com/`),are added to the frontier. URLs containing `#` are dropped. In addition, **every** `href` containing the string `usatoday.com` is queued as it is —any subdomain, Wayback Machine snapshots (`web.archive.org/web/…/https://www.usatoday.com/…`), and evenrelative or malformed links. Unlike the Euractiv crawler, `/video/` URLs are not filtered out (thecondition is commented out in the original script).4. **URL filtering.** Before fetching, a URL is skipped when it contains `/files/`, `.jpg`, `.pdf`, `.xml`, `.pptx`, `.shtml` or `.epub`, orwhen `len(url.split('/')) <= 4` (the bare host and single-segment URLs without a trailing slash).5. **Fetching.** The URL is sent as `POST {"url": "<url>"}` to the rendering service, whichanswers `{"html": "<page source>"}`. The service ran on the crawl operator's private network; itsaddress is removed from the published script and its implementation is not part of thisrepository. Each URL gets up to 10 attempts. An attempt is repeated when the request fails **orwhen the extracted `content` is empty**, so non-article pages (section fronts, author pages) arerequested 10 times before the crawler moves on — but their links are still followed. No requesttimeout was set.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 to1 unmodified linestart, so an interrupted crawl continues where it stopped. Creating a file named `killall.txt`in the working directory stops all workers cleanly.The crawler itself sets no proxies, no user agent and no politeness delay; it only talks to therendering service.**Paywall handling.** The crawler still contains Euractiv's check for an `<h2>` reading **"Want to keepreading?"** (the script was adapted from the Euractiv crawler), which never matches on USA Today, so ineffect no paywall filter was applied. A spot check of the bodies shows no metered-paywall teasers;subscription and newsletter prompts do appear inline (see the notes below).### 2. Article extraction`get_content()` reads the fields from the page's meta tags, JSON blocks and HTML, as follows:| Field | Source in the page ||---|---|| `title` | `og:title` meta tag || `content` | all `<p>` inside `<article class="primary-content">`, space-joined || `authors` | texts of all `<a class="authors">` || `description` | `description` from the first `ld+json` block || `keywords` | `<meta name="news_keywords">`, split on `,` (entries are not stripped) || `category` | first segment of `cst` in the page's `<script type="application/json">` || `subcategory` | second segment of that `cst` value || `dateCreated` | `dateCreated` from the first `ld+json` block || `datePublished` | `datePublished` from the first `ld+json` block || `dateModified` | `dateModified` from the first `ld+json` block || `primaryTag` | `primaryTag.name` from the `application/json` block || `contentId` | `contentId` from the `application/json` block (Gannett's numeric asset id) || `url` | the crawled URL |Each article is stored as a JSON file of the shape```json4 unmodified lines}```### 3. ConsolidationThe crawler's `pages/*.json` files were merged into one table (one column per field) and pushed tothe Hub. The notebook used for this step was not kept with the crawler, so it is not published here;what can be read off the published data is listed in the dataset-specific notes below.### Dataset-specific notes- **Empty headlines.** `title` is empty in 109 871 rows (14.7 %), almost all of them `/story/` pages on `www.` and `eu.usatoday.com` whose rendered HTML had no `og:title`. `description` and `content` are filled for these rows.- **No headline deduplication.** Besides the empty titles, 9 279 rows repeat a non-empty headline. URLs are unique, and 124 `contentId` values occur twice (mostly the same sports-betting article on `sportsbookwire.usatoday.com` and `sportsbookwire-eu.usatoday.com`).- **Hosts.** 341 142 rows come from `www.usatoday.com`, 245 599 from `eu.usatoday.com`, 146 680 from other `*.usatoday.com` sports sub-sites (`ftw.`, `billswire.`, `golfweek.`, `mmajunkie.` …) and 12 105 (1.6 %) are Wayback Machine snapshots, either as `https://web.archive.org/web/<timestamp>/…` or as a relative `/web/<timestamp>/…` path.- 887 URLs (0.1 %) are not well-formed absolute URLs: relative `/web/…` paths, `mailto:` links, doubled schemes such as `http://https://www.usatoday.com/…`. Another 0.2 % contain a double slash after the host (`https://eu.usatoday.com//story/…`) because relative links are joined as `base_url + href`.- **CMS keywords.** `keywords` is empty in 46 % of the rows. Where present it mixes topic tags with Gannett workflow and sentiment labels: 34 % of all rows contain one of `Overall Positive`, `Overall Neutral` or `Overall Negative`, and tags such as `Exclude Social Autopilot` or `Modular Story` are common. Because the meta tag is split on every `,`, tags that contain a comma are cut in two (`Washington, D.C.` becomes `Washington` and ` D.C.`), and the parts are not stripped: 4.7 % of the rows have a keyword with a leading space.- `authors` is empty in 49 % of the rows (93 % on the sports sub-sites).- `category` is empty in 0.9 % and `subcategory` in 18 % of the rows.- `dateCreated` equals `datePublished` in all but one row. One row has the placeholder `0001-01-01T00:00:00Z`; 64 rows are dated before 2012, and dense coverage starts in 2012.- Bodies contain inline promotional text ("Subscribe to our Sports newsletter now!", affiliate deals), and 11 498 rows end in a newsletter or subscription footer. 9 rows have an empty `content`.- The consolidation notebook for this dataset was not kept with the crawler, so it is not published here. The published data is sorted by `datePublished` (as a string), newest first, and contains no row with an empty `datePublished`.- The crawler imports `mechanicalsoup`, `fake_useragent`, `random` and `dateutil` without using them.### Reproducing the crawl```bashpip install requests beautifulsoup4 lxml python-dateutil mechanicalsoup fake-useragent \pandas datasets huggingface_hub tqdmmkdir usa_today_com && cd usa_today_comcurl -L -O https://huggingface.co/datasets/SinclairSchneider/usa_today_com/resolve/main/scraping/crawler.pycurl -L -O https://huggingface.co/datasets/SinclairSchneider/usa_today_com/resolve/main/scraping/.env.examplecp .env.example .env # set SCRAPER_RENDER_URL to your rendering servicepython crawler.py # writes pages/*.json; `touch killall.txt` to stop```The published `crawler.py` needs a rendering service with the contract described above —`POST {"url": …}` → `{"html": …}`, typically a small web app around a headless browser. Point`SCRAPER_RENDER_URL` at it; without it the script exits with a message. When this card was written(November 2026) a plain HTTP client was refused by the site with HTTP 402. The remainingsettings are optional and default to the values of the original crawl:| Variable | Meaning ||---|---|| `SCRAPER_RENDER_URL` | **Required.** Endpoint of the rendering service. || `SCRAPER_THREADS` | Worker processes (default 32). || `SCRAPER_TIMEOUT` | Seconds to wait for the rendering service per attempt (default: no timeout). || `SCRAPER_RETRIES` | Attempts per URL (default 10). || `SCRAPER_START_URL` | Seed URL. |No credentials, cookies or personal data are contained in the published code. See[`scraping/README.md`](./scraping/README.md) for details.**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 prefer23 unmodified lines```pythonfrom datasets import load_dataset, concatenate_datasetsoutlets = ["SinclairSchneider/usa_today_com", "SinclairSchneider/los_angeles_times_com"]parts = []for name in outlets:d = load_dataset(name, split="train").select_columns(["title", "content", "url"])4 unmodified lines## Limitations and biases- **Crawl, not archive.** Coverage is whatever was reachable by following links from the seed URLat crawl time. Articles that were deleted or orphaned before the crawl are missing, and oldcontent is covered less densely than recent content.- **No paywall filter.** No paywall filter was applied: whatever body text the rendered page contained was kept. Non-article page types (galleries, video pages, live tickers) are under-represented because they often have no extractable body text.- **Duplicates.** The data was not deduplicated by headline; the same story can appearunder several hosts or URLs (see the notes below).- **Noisy metadata.** Author, category and keyword fields come straight from the publisher's markup;empty values are common and labels are not harmonised across 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.- **No text normalisation.** Bodies are the concatenated paragraphs as published, includingtypographic quotes and residual boilerplate (newsletter and subscription prompts).## Licensing and intended use### Scientific research only — *Forschungsprivileg* (§ 60d UrhG)This dataset is made available **solely for the purpose of scientific research**. It was compiled bya German research institution, and the legal basis is the German text-and-data-mining exception forresearch, 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 out1 unmodified linecorpus 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. If you work outside the EU, check which rulesapply to your own use.- § 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 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 USA Today 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.11 unmodified lines```bibtex@misc{usa_today_com_dataset,title = {USA Today (usatoday.com): a corpus of English news articles},author = {Schneider, Sinclair},year = {2025},howpublished = {Hugging Face},4 unmodified lines## See also- The full [International Newspapers collection](https://huggingface.co/collections/SinclairSchneider/international-newspapers-6900fdd5083089f336574c82)- The [German Media collection](https://huggingface.co/collections/SinclairSchneider/german-media),built with a closely related crawler- Mirror of this dataset: [`NLP-UniBW/usa_today_com`](https://huggingface.co/datasets/NLP-UniBW/usa_today_com)12345672 unmodified lines101112131415161718192021222324252644 unmodified lines7172737475767778798081828329 unmodified lines1131141151161171181191201211221231 unmodified line12512612712812913013113213313413513613713813914014114219 unmodified lines16216316416516616716840 unmodified lines2092102112122132142152162172182192202212222232242252262272282292302312322332342352361 unmodified line2382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792804 unmodified lines28528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834923 unmodified lines3733743753763773783794 unmodified lines3843853863873883893903913923933943953963973983994004014024034044054064074084091 unmodified line41141241341441541641741841942042142242342442542642742842943043111 unmodified lines4434444454464474484494 unmodified lines454455456457---language:- enpretty_name: USA TODAY (usatoday.com)size_categories:- 100K<n<1Mtask_categories:2 unmodified lines- summarization- feature-extractiontags:- english- gannett- journalism- media- media-bias- national-daily- news- news-articles- research-only- text-and-data-mining- us-media- web-scrapingannotations_creators:- no-annotation44 unmodified linesdataset_size: 2952892502---# USA TODAY (usatoday.com)**745 945 English-language news articles** crawled from[`eu.usatoday.com`](https://eu.usatoday.com/) and published as a Hugging Face dataset.This is part of the [International Newspapers collection](https://huggingface.co/collections/SinclairSchneider/international-newspapers-6900fdd5083089f336574c82),a set of comparable corpora covering English-language newspapers and EU-affairs outlets, all built with the same crawler and the sameextraction pipeline so that they can be compared and combined directly.> ## ⚠️ For scientific research only>29 unmodified lines## About the source[USA TODAY](https://www.usatoday.com/) is a national daily newspaper in the United States,founded in 1982 by the Gannett Company and known for its concise, graphics-led format. It anchors theUSA TODAY Network, Gannett's group of several hundred local American newspapers, which means anoticeable share of nationally syndicated service, sport and lifestyle content alongside its ownnational reporting.## Dataset structure1 unmodified line| Column | Type | Description | Extracted from ||---|---|---|---|| `title` | `string` | Headline of the article. | `<meta property="og:title">` || `content` | `string` | Full plain-text body of the article. | all `<p>` inside `article.primary-content`, individually stripped and space-joined || `authors` | `list[string]` | — | all `a.authors` links, kept as a list || `description` | `string` | Teaser / meta description of the article. | `description` from `ld+json` || `keywords` | `list[string]` | Topic keywords / tags assigned by the publisher. | `<meta name="news_keywords">`, split on `,` || `category` | `string` | Section the article was published in. | the first segment of the `cst` path in the page's `application/json` state block || `subcategory` | `string` | Sub-section or kicker below the main section. | the second segment of the same `cst` path || `dateCreated` | `string` | Timestamp at which the CMS record was created. | `dateCreated` from `ld+json` || `datePublished` | `string` | Publication timestamp. | `datePublished` from `ld+json` || `dateModified` | `string` | Timestamp of the last editorial update. | `dateModified` from `ld+json` || `primaryTag` | `string` | — | `primaryTag.name` from the `application/json` state block || `contentId` | `int64` | — | `contentId` from the `application/json` state block — Gannett's internal article id || `url` | `string` | Canonical URL the article was fetched from. | the crawled URL |### Example record19 unmodified lines"U.S. Congress","Donald Trump","Government","…"],"category": "news","subcategory": "politics",40 unmodified lines## 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://eu.usatoday.com/story/news/world/2025/10/30/donald-trump-trade-tariffs-china-xi-jinping/86974396007/`) and discoverseverything else by following links.3. **Link discovery.** Every fetched page is parsed with BeautifulSoup/lxml; all `<a href>` valuesthat start with `https://eu.usatoday.com/` 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`, or when it has fewer than five pathsegments (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 to1 unmodified linestart, 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:** used — requests were sent through a rotating pool of forward proxies (the published script reproduces this via `SCRAPER_PROXIES`, see below)- **User-agent rotation:** yes, a random UA per request via `fake_useragent`- **Politeness delay:** none — throttling was handled by the proxy pool / retry loop- **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**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` | `<meta property="og:title">` || `content` | all `<p>` inside `article.primary-content`, individually stripped and space-joined || `authors` | all `a.authors` links, kept as a list || `description` | `description` from `ld+json` || `keywords` | `<meta name="news_keywords">`, split on `,` || `category` | the first segment of the `cst` path in the page's `application/json` state block || `subcategory` | the second segment of the same `cst` path || `dateCreated` | `dateCreated` from `ld+json` || `datePublished` | `datePublished` from `ld+json` || `dateModified` | `dateModified` from `ld+json` || `primaryTag` | `primaryTag.name` from the `application/json` state block || `contentId` | `contentId` from the `application/json` state block — Gannett's internal article id || `url` | the crawled URL |Two embedded data blocks are used: the standard `application/ld+json` block forthe dates and description, and Gannett's own `application/json` state block for the `cst` sectionpath, `primaryTag` and `contentId`.Each article is stored as a JSON file of the shape```json4 unmodified lines}```### 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=['content'])` removes duplicates — the same article is often reachableunder several URLs (print/mobile variants, tracking parameters, section mirrors), andthe body text is used as the identity key here because the same story appears under several headlines across the network.4. The frame is written to `usa_today_com.json` and pushed with`datasets.Dataset.from_pandas(df).push_to_hub("SinclairSchneider/usa_today_com")`.### Dataset-specific notes- The crawl targets the **EU edition host** `eu.usatoday.com`, the GDPR-reduced variant served to European visitors. Article text matches the US edition, but the set of reachable pages can differ.- Deduplication for this dataset uses the **body text**, not the headline: the USA TODAY Network republishes the same story under different headlines across its local titles.- The author column is named `authors` (plural) and holds a **list**.### Reproducing the crawl```bashpip install mechanicalsoup beautifulsoup4 lxml python-dateutil fake-useragent \pandas datasets huggingface_hub tqdmmkdir usa_today_com && cd usa_today_comcurl -L -O https://huggingface.co/datasets/SinclairSchneider/usa_today_com/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 prefer23 unmodified lines```pythonfrom datasets import load_dataset, concatenate_datasetsoutlets = ["SinclairSchneider/usa_today_com", "SinclairSchneider/tagesschau_de"]parts = []for name in outlets:d = load_dataset(name, split="train").select_columns(["title", "content", "url"])4 unmodified lines## 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 out1 unmodified linecorpus 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 USA TODAY 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.11 unmodified lines```bibtex@misc{usa_today_com_dataset,title = {USA TODAY (usatoday.com): a corpus of German news articles},author = {Schneider, Sinclair},year = {2025},howpublished = {Hugging Face},4 unmodified lines## See also- The full [International Newspapers collection](https://huggingface.co/collections/SinclairSchneider/international-newspapers-6900fdd5083089f336574c82)- Mirror of this dataset: [`NLP-UniBW/usa_today_com`](https://huggingface.co/datasets/NLP-UniBW/usa_today_com)
12345672 unmodified lines101112131415161718192021222324251 unmodified line272829303132333435363738# ---------------------------------------------------------------------------# crawler.py configuration for eu.usatoday.com## Copy this file to `.env` and fill in SCRAPER_RENDER_URL:## cp .env.example .env#2 unmodified lines## SCRAPER_THREADS=4 python crawler.py## Apart from the rendering endpoint, the defaults shown are exactly the values# that were used for the original crawl.# ---------------------------------------------------------------------------# === Rendering service (required) ==========================================# Every URL is POSTed as {"url": "..."} to this endpoint, which must answer# {"html": "<page source>"} - e.g. a small web app around a headless browser.SCRAPER_RENDER_URL=http://localhost:5000/scrap# === Crawler tuning ========================================================1 unmodified line# Number of worker processes sharing the URL frontier.#SCRAPER_THREADS=32# Seconds to wait for the rendering service per attempt. Unset = no timeout,# which is what the original crawl used.#SCRAPER_TIMEOUT=60# Attempts per URL before it is given up on (pages with an empty body are# retried as well).#SCRAPER_RETRIES=10# Seed URL the crawl starts from. Any article URL on the site works.12345672 unmodified lines101112131415161718192021222324252627282930313233343536373839401 unmodified line42434445464748495051# ---------------------------------------------------------------------------# crawler.py configuration for eu.usatoday.com## Copy this file to `.env` and uncomment the lines you need:## cp .env.example .env#2 unmodified lines## 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 ========================================================1 unmodified line# 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.
1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849503 unmodified lines5455565758591 unmodified line| File | Purpose ||---|---|| [`crawler.py`](./crawler.py) | Distributed whole-site crawler for `eu.usatoday.com`. Sends every URL to an HTML-rendering service and writes one JSON file per article to `pages/`. || [`.env.example`](./.env.example) | Configuration template. Copy to `.env` and set at least `SCRAPER_RENDER_URL`. |```bashpip install requests beautifulsoup4 lxml python-dateutil mechanicalsoup fake-useragent \pandas datasets huggingface_hub tqdmcp .env.example .env # set SCRAPER_RENDER_URLpython crawler.py # writes pages/*.json; `touch killall.txt` to stop```The consolidation notebook that merged `pages/*.json` into the published dataset was not kept with this crawler and is therefore not included; see the dataset card for what is known about that step.## The rendering serviceThe crawler never requests the site itself. For every URL it sends```httpPOST <SCRAPER_RENDER_URL>Content-Type: application/json{"url": "https://eu.usatoday.com/…"}```and expects a JSON answer of the form `{"html": "<page source>"}`. The original crawlused such a service on a private network; its address has been removed from thispublished copy and its implementation is not part of this repository. Any servicewith the same contract works — typically a small web app that loads the URL in aheadless browser and returns the rendered page source. When this was published(November 2026) a plain HTTP client was refused by the site with HTTP 402.## ConfigurationAll settings are read from the environment or from a `.env` file next to`crawler.py`. Apart from the rendering endpoint, the defaults are exactly thevalues used for the original crawl.| Variable | Meaning ||---|---|| `SCRAPER_RENDER_URL` | **Required.** Endpoint of the rendering service (see above). || `SCRAPER_THREADS` | Number of worker processes sharing the URL frontier. || `SCRAPER_TIMEOUT` | Seconds to wait for the rendering service per attempt. Unset = no timeout, as in the original crawl. || `SCRAPER_RETRIES` | Attempts per URL before giving up. A page whose extracted body is empty is retried too. || `SCRAPER_START_URL` | Seed URL the crawl starts from. |Environment variables take precedence over `.env`, so a single run can be3 unmodified linesSCRAPER_THREADS=4 python crawler.py```The scripts contain no credentials, cookies or personal data.Please crawl responsibly: honour `robots.txt` and the site's terms of use, keep1 unmodified line23456789101112131415161718192021222324252627282930313233343536373 unmodified lines41424344454647484950515253545556575859606162636465666768697071727374757677787980811 unmodified line| File | Purpose ||---|---|| [`crawler.py`](./crawler.py) | Distributed whole-site crawler for `eu.usatoday.com`. 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 tqdmpython crawler.py # writes pages/*.json; `touch killall.txt` to stopjupyter notebook finalize.ipynb```## ConfigurationAll 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 be3 unmodified linesSCRAPER_THREADS=4 python crawler.py```### ProxiesThe 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, keep
123456789101112131415161718192021221 unmodified line2425262728293031323334353637383911 unmodified lines51525354555657585960616263646566676869707116 unmodified lines88899091929394959697989910010110210310466 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921933 unmodified lines1971981992002012022032041 unmodified line20620720820921021121221338 unmodified lines252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335"""Whole-site crawler for eu.usatoday.com (USA Today).This is the crawler script behind the Hugging Face datasethttps://huggingface.co/datasets/SinclairSchneider/usa_today_com - see that dataset card for astep-by-step description of the pipeline and the known quirks of the data.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 byfollowing links (see ``get_urls()``).* Pages are not fetched directly: each URL is POSTed as ``{"url": ...}`` to anHTML-rendering service, which must answer ``{"html": "<page source>"}``.Set ``SCRAPER_RENDER_URL`` to such a service; the private address used forthe original crawl has been removed from this published copy.* ``get_content()`` turns an article page into a record; pages with an emptybody are retried and finally dropped. Each surviving article is written to``pages/<flattened-url>.json``.* Known and visited URLs are appended to ``data/thread_<id>_pages*.txt``, so aninterrupted crawl resumes where it left off. Create a file named1 unmodified lineUsage-----pip install requests beautifulsoup4 lxml python-dateutil mechanicalsoup fake-useragentSCRAPER_RENDER_URL=http://localhost:5000/scrap python crawler.py(``mechanicalsoup`` and ``fake-useragent`` are imported but not used.)Configuration-------------Copy ``.env.example`` to ``.env`` - the rendering endpoint, worker count,timeout, retries and the seed URL are all read from there (environmentvariables still win over the file).Please crawl responsibly: honour robots.txt and the site's terms of use, andlower the worker count unless you have the operator's permission.11 unmodified linesimport timeimport randomfrom fake_useragent import UserAgentimport requestsfrom dateutil.parser import parsebase_url = "https://eu.usatoday.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# fill in at least SCRAPER_RENDER_URL:## cp .env.example .env## Apart from the rendering endpoint, 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.16 unmodified lines_load_dotenv()# The original crawl did not fetch pages directly. Every URL was POSTed as# {"url": "<page url>"} to an HTML-rendering service on a private network,# which answered {"html": "<rendered page source>"}. That address has been# removed from this published copy; point SCRAPER_RENDER_URL at any service# with the same contract (e.g. a small web app around a headless browser).RENDER_URL = os.environ.get("SCRAPER_RENDER_URL", "").strip()NUM_THREADS = int(os.environ.get("SCRAPER_THREADS", "32"))MAX_RETRIES = int(os.environ.get("SCRAPER_RETRIES", "10"))START_URL = os.environ.get("SCRAPER_START_URL", "https://eu.usatoday.com/story/news/world/2025/10/30/donald-trump-trade-tariffs-china-xi-jinping/86974396007/")# seconds per call to the rendering service; unset = wait indefinitely, as in the original crawlREQUEST_TIMEOUT = float(os.environ["SCRAPER_TIMEOUT"]) if os.environ.get("SCRAPER_TIMEOUT", "").strip() else Nonedef log(number, url):if not os.path.isdir("log"):66 unmodified linesreturn dict_returndef get_urls(page_str):try: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:continueif url.startswith(base_url):return_urls.add(url)if "usatoday.com" in url:return_urls.add(url)if url.startswith("/"):url = base_url + urlreturn_urls.add(url)return return_urlsexcept:return set()def readSavedData(iId, sPageset, sPagesetVisited):if not os.path.isdir("data"):3 unmodified linesfor line in f:if "#" in line:continueline = line.replace("\n", "")if line != "":sPageset.add(line)if os.path.isfile("data/thread_"+str(iId)+"_pages_visited.txt"):1 unmodified linefor line in f:if "#" in line:continueline = line.replace("\n", "")if line != "":sPagesetVisited.add(line)def addStartChannel(sPage, iNumberOfThreads, lQueues):38 unmodified linesif sPage != "":f.write(sPage+"\n")def crawler(iId, iNumberOfThreads, lQueues):sPageset = set()sPagesetVisited = set()readSavedData(iId, sPageset, sPagesetVisited)while True:content = NonesPage = getNextPage(lQueues, iId, sPageset, sPagesetVisited)if sPage is None:breakif "#" in sPage:continueif (not "/files/" 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:response = requests.post(RENDER_URL, json={'url':sPage}, timeout=REQUEST_TIMEOUT)page_str = response.json().get('html')page_bs = BeautifulSoup(page_str, "lxml")pro_article = "Want to keep reading?" in [x.text.strip() for x in page_bs.find_all("h2")] if page_bs.find_all("h2") != None else Falseif pro_article == True:print("pay article")breaktry:content = get_content(sPage, page_str)except:error(iId, sPage)if content['content'] != '':breakelse:print("content==\"\" retry "+str(9-i)+" times.")except:print(sPage)print("retry")continueelse:page_str = ""if content == None:content = {'content':''}page_str = ""if content['content'] != '':file_path = sPage.replace(base_url+"/", "").replace("/", "_")[-200:]file_path = "pages/"+file_pathfile_path = file_path[:-1] if file_path.endswith("_") else file_pathfile_path = file_path+".json"content_json = json.dumps(content)with open(file_path, "w", encoding = "utf-8") as f:f.write(content_json)else:passif page_str == "":sPages = set()else: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 RENDER_URL:raise SystemExit("Set SCRAPER_RENDER_URL (environment or .env) to the rendering service ""this crawler sends every URL to - see the header of this file.")if not os.path.isdir("pages"):os.mkdir("pages")1234567891011121314151617181 unmodified line202122232425262728293031323334353611 unmodified lines484950515253545556575859606162636465666768697016 unmodified lines8788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513666 unmodified lines2032042052062072082092102112122132142152162172182192202212222232242252262272283 unmodified lines2322332342352362372382392402412422432442452462471 unmodified line24925025125225325425525625725825926026126226326438 unmodified lines303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442"""Whole-site crawler for eu.usatoday.com (USA TODAY).This is the exact script that produced the Hugging Face datasethttps://huggingface.co/datasets/SinclairSchneider/usa_today_com — 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 byfollowing links below ``https://eu.usatoday.com/``.* ``get_content()`` turns an article page into a record; pages with an emptybody 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 aninterrupted crawl resumes where it left off. Create a file named1 unmodified lineUsage-----pip install mechanicalsoup beautifulsoup4 lxml python-dateutil fake-useragentpython crawler.pyConfiguration-------------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.11 unmodified linesimport timeimport randomfrom fake_useragent import UserAgentfrom dateutil.parser import parseimport tracebackfrom datetime import datetimebase_url = "https://eu.usatoday.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.16 unmodified lines_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 blanklines and "#" comments allowed. This is the practicalform for a whole proxy farm: the pool can be swapped orregenerated 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 anempty 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:continueif "://" not in entry:entry = "http://" + entryif entry not in pool:pool.append(entry)return poolPROXY_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://eu.usatoday.com/story/news/world/2025/10/30/donald-trump-trade-tariffs-china-xi-jinping/86974396007/")def log(number, url):if not os.path.isdir("log"):66 unmodified linesreturn dict_returndef 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:continueif "golfweek" in url or "help.usatoday.com" in url or "mmajunkie.usatoday.com" in url or "ftw.usatoday.com" in url or "beta.usatoday.com" in url or "privacy-policy" in url or "/cookies" in url or "/privacy" in url or "/terms" in url or "/cookie-policy" in url or \"marketing.usatoday.com" in url or "login.usatoday.com" in url or "supportlocal.usatoday.com" in url or "newstips.usatoday.com" in url or "/accessibility" in url or "subscribe.usatoday.com" in url or url == base_url or "games.usatoday.com" in url or \"sportsweekly.usatoday.com" in url or "account.usatoday.com" in url or "/mobile-apps" in url or ".aspx" in url or ".jsp" in url or "/ethical-conduct" in url or "web.archive.org" in url:continueif "usatoday.com" in url:url = url.replace("https://www.usatoday.com", "https://eu.usatoday.com")url = url.replace("https://sportsbookwire.usatoday.com/", "https://sportsbookwire-eu.usatoday.com/")return_urls.add(url)else:continueif url.startswith("/"):url = base_url + urlreturn_urls.add(url)return return_urlsdef readSavedData(iId, sPageset, sPagesetVisited):if not os.path.isdir("data"):3 unmodified linesfor line in f:if "#" in line:continueif "golfweek" in line or "help.usatoday.com" in line or "mmajunkie.usatoday.com" in line or "ftw.usatoday.com" in line or "beta.usatoday.com" in line or "privacy-policy" in line or "/cookies" in line or "/privacy" in line or "/terms" in line or "/cookie-policy" in line or \"marketing.usatoday.com" in line or "login.usatoday.com" in line or "supportlocal.usatoday.com" in line or "newstips.usatoday.com" in line or "/accessibility" in line or "subscribe.usatoday.com" in line or line == base_url or "games.usatoday.com" in line or \"sportsweekly.usatoday.com" in line or "account.usatoday.com" in line or "/mobile-apps" in line or ".aspx" in line or ".jsp" in line or "/ethical-conduct" in line or "web.archive.org" in line:continueif "usatoday.com" not in line:continueline = line.replace("\n", "")if line != "":line = line.replace("https://www.usatoday.com", "https://eu.usatoday.com")line = line.replace("https://sportsbookwire.usatoday.com/", "https://sportsbookwire-eu.usatoday.com/")sPageset.add(line)if os.path.isfile("data/thread_"+str(iId)+"_pages_visited.txt"):1 unmodified linefor line in f:if "#" in line:continueif "golfweek" in line or "help.usatoday.com" in line or "mmajunkie.usatoday.com" in line or "ftw.usatoday.com" in line or "beta.usatoday.com" in line or "privacy-policy" in line or "/cookies" in line or "/privacy" in line or "/terms" in line or "/cookie-policy" in line or \"marketing.usatoday.com" in line or "login.usatoday.com" in line or "supportlocal.usatoday.com" in line or "newstips.usatoday.com" in line or "/accessibility" in line or "subscribe.usatoday.com" in line or line == base_url or "games.usatoday.com" in line or \"sportsweekly.usatoday.com" in line or "account.usatoday.com" in line or "/mobile-apps" in line or ".aspx" in line or ".jsp" in line or "/ethical-conduct" in line or "web.archive.org" in line:continueif "usatoday.com" not in line:continueline = line.replace("\n", "")if line != "":line = line.replace("https://www.usatoday.com", "https://eu.usatoday.com")line = line.replace("https://sportsbookwire.usatoday.com/", "https://sportsbookwire-eu.usatoday.com/")sPagesetVisited.add(line)def addStartChannel(sPage, iNumberOfThreads, lQueues):38 unmodified linesif sPage != "":f.write(sPage+"\n")def log_crash(worker_id, where):try:if not os.path.isdir("crashes"):os.mkdir("crashes")fname = os.path.join("crashes", f"worker_{worker_id}_{int(time.time())}.log")with open(fname, "w", encoding="utf-8") as f:f.write(f"[{datetime.utcnow().isoformat()}Z] Crash in {where}\n")f.write(traceback.format_exc())except Exception:passdef crawler(iId, iNumberOfThreads, lQueues):try:sPageset = set()sPagesetVisited = set()readSavedData(iId, sPageset, sPagesetVisited)while True:sPage = getNextPage(lQueues, iId, sPageset, sPagesetVisited)sPageOriginal = sPagesPage = sPage.replace("http:", "https:")sPage = sPage.replace("https://www.usatoday.com", "https://eu.usatoday.com")sPage = sPage.replace("https://usatoday.com", "https://eu.usatoday.com")sPage = sPage.replace("https://sportsbookwire.usatoday.com/", "https://sportsbookwire-eu.usatoday.com/")if sPage is None:breakif len(sPage.split("https://")) > 2:sPage = "https://" + sPage.split("https://")[-1]if "#" in sPage:addVisitedPages(sPage, sPagesetVisited, iId)addVisitedPages(sPage.replace("eu.usatoday.com", "usatoday.com"), sPagesetVisited, iId)continueif "golfweek" in sPage or "help.usatoday.com" in sPage or "mmajunkie.usatoday.com" in sPage or "ftw.usatoday.com" in sPage or "beta.usatoday.com" in sPage or "privacy-policy" in sPage or "/cookies" in sPage or "/privacy" in sPage or "/terms" in sPage or "/cookie-policy" in sPage or \"marketing.usatoday.com" in sPage or "login.usatoday.com" in sPage or "supportlocal.usatoday.com" in sPage or "newstips.usatoday.com" in sPage or "/accessibility" in sPage or "subscribe.usatoday.com" in sPage or sPage == base_url or "games.usatoday.com" in sPage or \"sportsweekly.usatoday.com" in sPage or "account.usatoday.com" in sPage or "/mobile-apps" in sPage or ".aspx" in sPage or ".jsp" in sPage or "/ethical-conduct" in sPage or "web.archive.org" in sPage:addVisitedPages(sPage, sPagesetVisited, iId)addVisitedPages(sPage.replace("eu.usatoday.com", "usatoday.com"), sPagesetVisited, iId)continueif "usatoday.com" not in sPage:addVisitedPages(sPage, sPagesetVisited, iId)addVisitedPages(sPage.replace("eu.usatoday.com", "usatoday.com"), sPagesetVisited, iId)continuesPage = sPage.replace("https://www.usatoday.com", "https://eu.usatoday.com")sPage = sPage.replace("https://sportsbookwire.usatoday.com/", "https://sportsbookwire-eu.usatoday.com/")print(sPage)page_str = ""if (not "/files/" in sPage) and \(not "/video/" 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_POOLproxy = lproxies[int((int(time.time())/1)+iId)%len(lproxies)] if lproxies else Noneproxy = lproxies[int((int(time.time())/1))%len(lproxies)] if lproxies else Noneproxy = lproxies[int(iId)%len(lproxies)] if lproxies else Noneproxies = {'https': proxy, 'http': proxy} if proxy else {}browser = mechanicalsoup.StatefulBrowser()ua = UserAgent()browser.set_user_agent(ua.random)browser.session.proxies = proxiesbrowser.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)continueif "You don't have permission to access" in page_str:print("error, we will wait a moment and continue")time.sleep(1)continueraw(iId, sPage, page_str)breakexcept:print(sPage)print("retry")browser.close()continuebrowser.close()else:page_str = ""try:content = get_content(sPage, page_str)except:error(iId, sPage)addVisitedPages(sPage, sPagesetVisited, iId)addVisitedPages(sPage.replace("eu.usatoday.com", "usatoday.com"), sPagesetVisited, iId)if content['content'] != '':file_path = sPage.replace(base_url+"/", "").replace("/", "_")[-200:]file_path = file_path.replace("https", "")file_path = file_path.replace("http", "").replace(":", "")file_path = "pages/"+file_pathfile_path = file_path[:-1] if file_path.endswith("_") else file_pathfile_path = file_path+".json"content_json = json.dumps(content)with open(file_path, "w", encoding = "utf-8") as f:f.write(content_json)else:passsPages = get_urls(page_str)addPagesToVisit(sPages, iNumberOfThreads, lQueues)addVisitedPages(sPageOriginal, sPagesetVisited, iId)addVisitedPages(sPage, sPagesetVisited, iId)addVisitedPages(sPage.replace("eu.usatoday.com", "usatoday.com"), sPagesetVisited, iId)print("Thread: " + str(iId) + " chanels visited: " + str(len(sPagesetVisited)) + " channels to visit: " + str(len(sPageset - sPagesetVisited)))except BaseException:log_crash(iId, "crawler")raisedef main():if not os.path.isdir("pages"):os.mkdir("pages")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# `USA TODAY (usatoday.com)` — consolidation notebook\n", "\n", "This notebook is the second half of the pipeline behind\n", "[`SinclairSchneider/usa_today_com`](https://huggingface.co/datasets/SinclairSchneider/usa_today_com).\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 body text (`drop_duplicates(subset=['content'])`),\n", "4. writes `usa_today_com.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/y_sports_college_ucla_baseball_2025_06_03_utsa-baseball-proved-toughness-ucla-super-regional_84004356007_?taid=683f2a449847150001c27a2b&utm_campaign=trueanthem&utm_medium=trueanthem&utm_source=twitter.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", "authors = []\n", "description = []\n", "keywords = []\n", "category = []\n", "subcategory = []\n", "dateCreated = []\n", "datePublished = []\n", "dateModified = []\n", "primaryTag = []\n", "contentId = []\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", " authors.append(d['additional_attributes']['authors'])\n", " description.append(d['additional_attributes']['description'])\n", " keywords.append(d['additional_attributes']['keywords'])\n", " category.append(d['additional_attributes']['category'])\n", " subcategory.append(d['additional_attributes']['subcategory'])\n", " dateCreated.append(d['additional_attributes']['dateCreated'])\n", " datePublished.append(d['additional_attributes']['datePublished'])\n", " dateModified.append(d['additional_attributes']['dateModified'])\n", " primaryTag.append(d['additional_attributes']['primaryTag'])\n", " contentId.append(d['additional_attributes']['contentId'])\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", " 'authors':authors,\n", " 'description':description,\n", " 'keywords':keywords,\n", " 'category':category,\n", " 'subcategory':subcategory,\n", " 'dateCreated':dateCreated,\n", " 'datePublished':datePublished,\n", " 'dateModified':dateModified,\n", " 'primaryTag':primaryTag,\n", " 'contentId':contentId,\n", " 'url':url,\n", " }\n", ")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df['keywords']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = df.drop_duplicates(subset=['content'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "len(df)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = df[df['datePublished']!=\"\"]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = df.sort_values(by=['datePublished'], ascending=False).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(\"usa_today_com.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/usa_today_com\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ds.push_to_hub(\"NLP-UniBW/usa_today_com\")" ] } ], "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+127-152
scraping/.env.example+25-12
scraping/README.md+51-29
scraping/crawler.py+222-115
scraping/finalize.ipynbAdded+233
scraping/proxies.example.txtAdded+15