SinclairSchneider commited on
Commit
6800ab7
·
verified ·
1 Parent(s): ac8347b

Add detailed dataset card and the scraping pipeline used to build it

Browse files
README.md CHANGED
@@ -1,4 +1,41 @@
1
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  dataset_info:
3
  features:
4
  - name: title
@@ -31,17 +68,375 @@ dataset_info:
31
  num_examples: 122268
32
  download_size: 420200866
33
  dataset_size: 715885507
34
- configs:
35
- - config_name: default
36
- data_files:
37
- - split: train
38
- path: data/train-*
39
- language:
40
- - en
41
- tags:
42
- - Newspaper
43
- - Europe
44
- - Politics
45
- size_categories:
46
- - 100K<n<1M
47
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language:
3
+ - en
4
+ pretty_name: POLITICO Europe (politico.eu)
5
+ size_categories:
6
+ - 100K<n<1M
7
+ task_categories:
8
+ - text-generation
9
+ - text-classification
10
+ - summarization
11
+ - feature-extraction
12
+ tags:
13
+ - brussels
14
+ - english
15
+ - eu-affairs
16
+ - journalism
17
+ - media
18
+ - media-bias
19
+ - news
20
+ - news-articles
21
+ - policy-journalism
22
+ - political-news
23
+ - research-only
24
+ - text-and-data-mining
25
+ - web-scraping
26
+ annotations_creators:
27
+ - no-annotation
28
+ language_creators:
29
+ - found
30
+ multilinguality:
31
+ - monolingual
32
+ source_datasets:
33
+ - original
34
+ configs:
35
+ - config_name: default
36
+ data_files:
37
+ - split: train
38
+ path: data/train-*
39
  dataset_info:
40
  features:
41
  - name: title
 
68
  num_examples: 122268
69
  download_size: 420200866
70
  dataset_size: 715885507
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  ---
72
+
73
+ # POLITICO Europe (politico.eu)
74
+
75
+ **122 268 English-language news articles** crawled from
76
+ [`www.politico.eu`](https://www.politico.eu/) and published as a Hugging Face dataset.
77
+ This is part of the [International Newspapers collection](https://huggingface.co/collections/SinclairSchneider/international-newspapers-6900fdd5083089f336574c82),
78
+ a set of comparable corpora covering English-language newspapers and EU-affairs outlets, all built with the same crawler and the same
79
+ extraction pipeline so that they can be compared and combined directly.
80
+
81
+ > ## ⚠️ For scientific research only
82
+ >
83
+ > This corpus is published **exclusively for scientific research** under the German
84
+ > research exception for text and data mining — the *Forschungsprivileg* of
85
+ > **§ 60d UrhG** (implementing Art. 3 of EU Directive 2019/790). The article texts remain
86
+ > the copyright of their publisher and are **not** licensed for commercial use,
87
+ > redistribution, or republication. By downloading it you confirm that you use it for
88
+ > non-commercial scientific research. See [Licensing and intended use](#licensing-and-intended-use).
89
+ >
90
+ > The articles are reproduced verbatim from the publisher's website; their content expresses
91
+ > the views of that publisher, not of the dataset author.
92
+
93
+ ## At a glance
94
+
95
+ | | |
96
+ |---|---|
97
+ | **Source** | [`www.politico.eu`](https://www.politico.eu/) |
98
+ | **Rows** | 122 268 |
99
+ | **Columns** | 12 (`title`, `content`, `author`, `description`, `keywords`, `category`, `countries`, `dateCreated`, `datePublished`, `dateModified`, `post_id`, `url`) |
100
+ | **Language** | English (`en`) |
101
+ | **Split** | `train` (single split) |
102
+ | **Format** | Parquet, 2 shards, ≈ 401 MB download / 683 MB in memory |
103
+ | **Intended use** | Scientific research only (*Forschungsprivileg*, § 60d UrhG) |
104
+ | **Mirror** | [`NLP-UniBW/politico_eu`](https://huggingface.co/datasets/NLP-UniBW/politico_eu) |
105
+
106
+ ```python
107
+ from datasets import load_dataset
108
+
109
+ ds = load_dataset("SinclairSchneider/politico_eu", split="train")
110
+ print(ds[0]["title"])
111
+ ```
112
+
113
+ ## About the source
114
+
115
+ [POLITICO Europe](https://www.politico.eu/) is a Brussels-based news organisation covering
116
+ European Union politics and policy. It launched in 2015 as a joint venture between the American
117
+ outlet POLITICO and the German publisher Axel Springer SE, which took full ownership of POLITICO
118
+ worldwide in 2021. Its newsroom is aimed primarily at EU policy professionals — officials,
119
+ lobbyists, diplomats and national correspondents in Brussels — and its coverage is organised
120
+ around the Commission, Parliament and Council, national capitals, and sectoral policy beats. A large
121
+ part of its output, the POLITICO Pro tier, is subscription-only and therefore outside this dataset.
122
+
123
+ ## Dataset structure
124
+
125
+ Single `train` split with 122 268 rows and the following columns:
126
+
127
+ | Column | Type | Description | Extracted from |
128
+ |---|---|---|---|
129
+ | `title` | `string` | Headline of the article. | `<meta property="og:title">` |
130
+ | `content` | `string` | Full plain-text body of the article. | all `<p>` inside the article body container `<article class="article">`, space-joined |
131
+ | `author` | `string` | Author(s) as published by the outlet. | the first entry of `author` in `ld+json` |
132
+ | `description` | `string` | Teaser / meta description of the article. | `description` from `ld+json` |
133
+ | `keywords` | `list[string]` | Topic keywords / tags assigned by the publisher. | `keywords` from `ld+json` |
134
+ | `category` | `string` | Section the article was published in. | `articleSection` from `ld+json` |
135
+ | `countries` | `list[string]` | — | the country tag links in `div.tags__taxonomy--country` — the EU member states the CMS associates with the article |
136
+ | `dateCreated` | `string` | Timestamp at which the CMS record was created. | `dateCreated` from `ld+json` |
137
+ | `datePublished` | `string` | Publication timestamp. | `datePublished` from `ld+json` |
138
+ | `dateModified` | `string` | Timestamp of the last editorial update. | `dateModified` from `ld+json` |
139
+ | `post_id` | `int64` | — | `post_id` from the `custom_metadata` object inside `ld+json` — POLITICO's internal article id |
140
+ | `url` | `string` | Canonical URL the article was fetched from. | the crawled URL |
141
+
142
+ ### Example record
143
+
144
+ ```json
145
+ {
146
+ "title": "Home and Away",
147
+ "content": "AI generated Text-to-speech Presented by Intuit By DAN BLOOM with BETHANY DAWSON PRESENTED BY Send tips here | Subscribe for free | Listen to Playbook and view in your browser Good Monday morning. This is Dan Bloom. HOME (OFFICE) AND AWAY: Keir Starmer will spend the day in Turkey finalizing a deal to sell fighter jets — but his efforts look set to be buried (again) by a blizzard of crime, justic …",
148
+ "author": "Dan Bloom",
149
+ "description": "",
150
+ "keywords": [],
151
+ "category": "Uncategorized",
152
+ "countries": [],
153
+ "dateCreated": "2025-10-27T07:00:46Z",
154
+ "datePublished": "2025-10-27T07:00:46Z",
155
+ "dateModified": "2025-10-27T07:01:10Z",
156
+ "post_id": 7395360,
157
+ "url": "https://www.politico.eu/newsletter/london-playbook/home-and-away/"
158
+ }
159
+ ```
160
+
161
+ ## Temporal coverage
162
+
163
+ The `datePublished` column could be parsed for **122 268 of 122 268** rows (100.0 %). Those rows span **1995-09-20 → 2025-10-29**.
164
+
165
+ | Year | Articles | |
166
+ |---:|---:|:---|
167
+ | 1995 | 627 | `██` |
168
+ | 1996 | 1 873 | `█████` |
169
+ | 1997 | 2 069 | `█████` |
170
+ | 1998 | 2 151 | `██████` |
171
+ | 1999 | 1 865 | `█████` |
172
+ | 2000 | 1 720 | `█████` |
173
+ | 2001 | 1 822 | `█████` |
174
+ | 2002 | 2 152 | `██████` |
175
+ | 2003 | 2 262 | `██████` |
176
+ | 2004 | 1 954 | `█████` |
177
+ | 2005 | 2 196 | `██████` |
178
+ | 2006 | 2 215 | `██████` |
179
+ | 2007 | 2 066 | `█████` |
180
+ | 2008 | 3 070 | `████████` |
181
+ | 2009 | 2 678 | `███████` |
182
+ | 2010 | 2 472 | `███████` |
183
+ | 2011 | 2 456 | `██████` |
184
+ | 2012 | 2 389 | `██████` |
185
+ | 2013 | 2 359 | `██████` |
186
+ | 2014 | 3 025 | `████████` |
187
+ | 2015 | 4 893 | `█████████████` |
188
+ | 2016 | 8 177 | `██████████████████████` |
189
+ | 2017 | 8 501 | `██████████████████████` |
190
+ | 2018 | 6 830 | `██████████████████` |
191
+ | 2019 | 5 873 | `████████████████` |
192
+ | 2020 | 6 225 | `████████████████` |
193
+ | 2021 | 6 589 | `█████████████████` |
194
+ | 2022 | 6 947 | `██████████████████` |
195
+ | 2023 | 8 098 | `█████████████████████` |
196
+ | 2024 | 9 085 | `████████████████████████` |
197
+ | 2025 | 7 629 | `████████████████████` |
198
+
199
+ ## How the data was collected
200
+
201
+ The whole pipeline is contained in this repository under [`scraping/`](./scraping) and consists
202
+ of two steps: a distributed crawler that walks the site and writes one JSON file per article, and
203
+ a consolidation notebook that merges those files into the dataset you are reading.
204
+
205
+ ### 1. Crawling — [`scraping/crawler.py`](./scraping/crawler.py)
206
+
207
+ The crawler is a breadth-first whole-site crawler built on
208
+ [MechanicalSoup](https://mechanicalsoup.readthedocs.io/) and `multiprocessing`:
209
+
210
+ 1. **Sharded frontier.** 32 worker processes each own one `multiprocessing.Manager().Queue()`.
211
+ A URL is assigned to a worker by `int(md5(url).hexdigest(), 16) % 32`, so every URL is always
212
+ handled by the same worker and no locking or cross-process deduplication is needed.
213
+ 2. **Seed.** The crawl is seeded with a single article URL
214
+ (`https://www.politico.eu/article/swedens-still-ahead-in-the-preparedness-game-and-now-it-means-business`) and discovers
215
+ everything else by following links.
216
+ 3. **Link discovery.** Every fetched page is parsed with BeautifulSoup/lxml; all `<a href>` values
217
+ that start with `https://www.politico.eu/` or with `/` (which are then made absolute) are added to the
218
+ frontier. URLs containing `#` are dropped.
219
+ 4. **URL filtering.** Before fetching, a URL is skipped when it contains `/files/`, `/video/`,
220
+ `.jpg`, `.pdf`, `.xml`, `.pptx`, `.shtml` or `.epub`, or when it has fewer than five path
221
+ segments (which filters out section index pages).
222
+ 5. **Fetching.** Each URL gets up to 10 attempts with a 10 s timeout.
223
+ 6. **Extraction.** `get_content()` turns the HTML into a record (see below). Only pages with a
224
+ non-empty `content` are written out, as `pages/<flattened-url>.json`.
225
+ 7. **Resumability.** Each worker appends every known and every visited URL to
226
+ `data/thread_<id>_pages.txt` and `data/thread_<id>_pages_visited.txt`, and re-reads them on
227
+ start, so an interrupted crawl continues where it stopped. Creating a file named `killall.txt`
228
+ in the working directory stops all workers cleanly.
229
+
230
+ Crawler settings used for this site:
231
+
232
+ - **Worker processes:** 32 (`iNumberOfThreads = 32`)
233
+ - **Retries per URL:** 10, with a 10-second socket timeout per attempt
234
+ - **Proxy pool:** used — requests were sent through a rotating pool of forward proxies (the published script reproduces this via `SCRAPER_PROXIES`, see below)
235
+ - **User-agent rotation:** yes, a random UA per request via `fake_useragent`
236
+ - **Politeness delay:** none — throttling was handled by the proxy pool / retry loop
237
+ - **Bot-challenge handling:** responses containing `#challenge-error-text` or `You don't have permission to access` are discarded and retried after a short pause
238
+ - **Raw HTML dump:** enabled (`raw/`), used for debugging the parser
239
+
240
+ **Paywall handling.** The site serves its articles without a paywall, so no paywall filter was necessary.
241
+
242
+ ### 2. Article extraction
243
+
244
+ `get_content()` reads the fields from the page's JSON-LD (`<script type="application/ld+json">`)
245
+ and/or its HTML, as follows:
246
+
247
+ | Field | Source in the page |
248
+ |---|---|
249
+ | `title` | `<meta property="og:title">` |
250
+ | `content` | all `<p>` inside the article body container `<article class="article">`, space-joined |
251
+ | `author` | the first entry of `author` in `ld+json` |
252
+ | `description` | `description` from `ld+json` |
253
+ | `keywords` | `keywords` from `ld+json` |
254
+ | `category` | `articleSection` from `ld+json` |
255
+ | `countries` | the country tag links in `div.tags__taxonomy--country` — the EU member states the CMS associates with the article |
256
+ | `dateCreated` | `dateCreated` from `ld+json` |
257
+ | `datePublished` | `datePublished` from `ld+json` |
258
+ | `dateModified` | `dateModified` from `ld+json` |
259
+ | `post_id` | `post_id` from the `custom_metadata` object inside `ld+json` — POLITICO's internal article id |
260
+ | `url` | the crawled URL |
261
+
262
+ `custom_metadata` arrives as a JSON string nested inside the JSON-LD block, so it is
263
+ parsed twice: once for the outer block and once for the embedded object that carries `post_id`.
264
+
265
+ Each article is stored as a JSON file of the shape
266
+
267
+ ```json
268
+ {
269
+ "title": "…",
270
+ "content": "…",
271
+ "additional_attributes": { "author": "…", "description": "…", "keywords": "…", "category": "…", "countries": "…", "dateCreated": "…", "datePublished": "…", "dateModified": "…", "post_id": "…", "url": "…" }
272
+ }
273
+ ```
274
+
275
+ ### 3. Consolidation — [`scraping/finalize.ipynb`](./scraping/finalize.ipynb)
276
+
277
+ 1. `glob("pages/*.json")` collects every article file.
278
+ 2. The nested records are flattened into one `pandas.DataFrame` column per field.
279
+ 3. `df.drop_duplicates(subset=['title'])` removes duplicates — the same article is often reachable
280
+ under several URLs (print/mobile variants, tracking parameters, section mirrors), and
281
+ the headline is the most reliable identity key available.
282
+ 4. The frame is written to `politico_eu.json` and pushed with
283
+ `datasets.Dataset.from_pandas(df).push_to_hub("SinclairSchneider/politico_eu")`.
284
+
285
+ ### Dataset-specific notes
286
+
287
+ - `countries` is the publisher's own geographic tagging, not an extraction from the text; it is empty for articles the CMS did not tag.
288
+
289
+ ### Reproducing the crawl
290
+
291
+ ```bash
292
+ pip install mechanicalsoup beautifulsoup4 lxml python-dateutil fake-useragent \
293
+ pandas datasets huggingface_hub tqdm
294
+
295
+ mkdir politico_eu && cd politico_eu
296
+ curl -L -O https://huggingface.co/datasets/SinclairSchneider/politico_eu/resolve/main/scraping/crawler.py
297
+
298
+ python crawler.py # writes pages/*.json; `touch killall.txt` to stop
299
+ jupyter notebook finalize.ipynb
300
+ ```
301
+
302
+ #### Routing the crawl through your own proxies
303
+
304
+ The original crawl ran behind a pool of forward proxies on a private network. Those addresses are
305
+ infrastructure-specific and have been **removed** from the published script. Instead, `crawler.py`
306
+ reads the `SCRAPER_PROXIES` environment variable: a comma-separated list of proxies, written with
307
+ or without a scheme (`http://` is assumed when none is given). One entry is picked per request, so
308
+ a pool spreads the load across several exits.
309
+
310
+ ```bash
311
+ # a single proxy
312
+ export SCRAPER_PROXIES="proxy-a.example.com:3128"
313
+
314
+ # a pool, rotated per request
315
+ export SCRAPER_PROXIES="proxy-a.example.com:3128,proxy-b.example.com:3128"
316
+
317
+ # with an explicit scheme and credentials
318
+ export SCRAPER_PROXIES="http://user:pass@proxy.example.com:3128"
319
+
320
+ # SOCKS, if PySocks is installed
321
+ export SCRAPER_PROXIES="socks5://localhost:9050"
322
+
323
+ # back to a direct connection — this is the default
324
+ unset SCRAPER_PROXIES
325
+
326
+ python crawler.py
327
+ ```
328
+
329
+ Internally this becomes `requests`' standard `{'http': …, 'https': …}` proxy mapping; with the
330
+ variable unset the mapping is empty and the crawler connects directly. No credentials, cookies or
331
+ personal data are contained in the published code.
332
+
333
+ **Please crawl responsibly:** respect `robots.txt` and the site's terms of use, keep the
334
+ concurrency far below the 32 workers used here unless you have the site's permission, and prefer
335
+ this published dataset over re-crawling.
336
+
337
+ ## Usage
338
+
339
+ ```python
340
+ from datasets import load_dataset
341
+ import pandas as pd
342
+
343
+ ds = load_dataset("SinclairSchneider/politico_eu", split="train")
344
+
345
+ # stream instead of downloading everything
346
+ stream = load_dataset("SinclairSchneider/politico_eu", split="train", streaming=True)
347
+ print(next(iter(stream))["title"])
348
+
349
+ # as a DataFrame
350
+ df = ds.to_pandas()
351
+ df["datePublished"] = pd.to_datetime(df["datePublished"], errors="coerce", utc=True, format="mixed")
352
+ recent = df[df["datePublished"].dt.year >= 2024]
353
+ print(len(recent), "articles from 2024 onwards")
354
+ ```
355
+
356
+ Combining several outlets into one comparative corpus:
357
+
358
+ ```python
359
+ from datasets import load_dataset, concatenate_datasets
360
+
361
+ outlets = ["SinclairSchneider/politico_eu", "SinclairSchneider/tagesschau_de"]
362
+ parts = []
363
+ for name in outlets:
364
+ d = load_dataset(name, split="train").select_columns(["title", "content", "url"])
365
+ parts.append(d.add_column("outlet", [name.split("/")[-1]] * len(d)))
366
+ corpus = concatenate_datasets(parts)
367
+ ```
368
+
369
+ ## Limitations and biases
370
+
371
+ - **Crawl, not archive.** Coverage is whatever was reachable by following links from the seed URL
372
+ at crawl time. Articles that were deleted, depublished or orphaned before the crawl are missing,
373
+ and old content is covered less densely than recent content.
374
+ - **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.
375
+ - **Deduplication by headline.** Two genuinely different articles with an identical headline
376
+ (common for recurring formats such as weather or daily briefings) collapse into one row.
377
+ - **Noisy metadata.** `author`, `category` and `keywords` come straight from the publisher's markup,
378
+ which changed over the years; empty strings are common and category labels are not harmonised
379
+ across outlets.
380
+ - **Editorial perspective.** This is the output of a single outlet. Any model trained on it alone
381
+ inherits that outlet's selection of topics, framing and vocabulary — which is exactly why the
382
+ collection provides the same pipeline across the political spectrum.
383
+ - **No text normalisation.** Bodies are the concatenated paragraphs as published, including
384
+ typographic quotes, soft hyphens and occasional residual boilerplate.
385
+
386
+ ## Licensing and intended use
387
+
388
+ ### Scientific research only — *Forschungsprivileg* (§ 60d UrhG)
389
+
390
+ This dataset is made available **solely for the purpose of scientific research**. The legal basis
391
+ is the German text-and-data-mining exception for research, the so-called **Forschungsprivileg**:
392
+
393
+ - **§ 60d UrhG** — *Text und Data Mining für Zwecke der wissenschaftlichen Forschung* — allows
394
+ research organisations to make reproductions of lawfully accessible works in order to carry out
395
+ text and data mining for **non-commercial** scientific research, and to share the resulting
396
+ corpus with a specifically limited circle of people for joint research and with individual third
397
+ parties for the purpose of quality assurance.
398
+ - It implements **Art. 3 of Directive (EU) 2019/790** (the DSM Directive); comparable research
399
+ exceptions exist in the other EU member states.
400
+ - § 60d UrhG does **not** cover commercial exploitation. Research organisations that give a
401
+ commercial enterprise preferential access are explicitly excluded from the privilege.
402
+
403
+ ### What this means for you
404
+
405
+ ✅ **Permitted** — using the corpus for non-commercial scientific research: text and data mining,
406
+ corpus linguistics, media-bias and discourse analysis, training and evaluating research models,
407
+ reproducing published findings, and quality checks by individual third parties.
408
+
409
+ ❌ **Not permitted** — commercial use or commercial model training; redistributing or republishing
410
+ the article texts; presenting the texts as your own; building products or services on the article
411
+ texts; any use that substitutes for reading the publisher's own website.
412
+
413
+ The **article texts remain the copyright of POLITICO Europe and its publisher.** No licence to them is
414
+ granted or implied by this repository. Only the crawling and extraction code in `scraping/` is
415
+ offered for free reuse.
416
+
417
+ If your intended use falls outside the research exception, obtain permission from the rights
418
+ holder, or use only the derived, non-expressive data (statistics, embeddings, counts). Note that
419
+ § 60d UrhG also expects research corpora to be deleted once they are no longer needed for the
420
+ research purpose, with archiving permitted at trusted institutions.
421
+
422
+ If you are a rights holder and want content removed, please open a discussion on this repository.
423
+
424
+ > This section is an orientation for researchers, not legal advice. Responsibility for your own
425
+ > use of the data remains with you and your institution.
426
+
427
+ ## Citation
428
+
429
+ ```bibtex
430
+ @misc{politico_eu_dataset,
431
+ title = {POLITICO Europe (politico.eu): a corpus of German news articles},
432
+ author = {Schneider, Sinclair},
433
+ year = {2025},
434
+ howpublished = {Hugging Face},
435
+ url = {https://huggingface.co/datasets/SinclairSchneider/politico_eu}
436
+ }
437
+ ```
438
+
439
+ ## See also
440
+
441
+ - The full [International Newspapers collection](https://huggingface.co/collections/SinclairSchneider/international-newspapers-6900fdd5083089f336574c82)
442
+ - Mirror of this dataset: [`NLP-UniBW/politico_eu`](https://huggingface.co/datasets/NLP-UniBW/politico_eu)
scraping/.env.example ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---------------------------------------------------------------------------
2
+ # crawler.py configuration for www.politico.eu
3
+ #
4
+ # Copy this file to `.env` and uncomment the lines you need:
5
+ #
6
+ # cp .env.example .env
7
+ #
8
+ # Variables that are already set in the real environment take precedence over
9
+ # this file, so a single run can still be overridden on the command line:
10
+ #
11
+ # SCRAPER_THREADS=4 python crawler.py
12
+ #
13
+ # Everything here is optional - the defaults shown are exactly the values that
14
+ # were used for the original crawl.
15
+ # ---------------------------------------------------------------------------
16
+
17
+
18
+ # === Proxies ===============================================================
19
+
20
+ # Inline pool. Separate entries with commas, semicolons, spaces or newlines.
21
+ # A scheme is optional - "http://" is assumed when none is given. One entry is
22
+ # picked per request, so several entries spread the load over several exits.
23
+ #SCRAPER_PROXIES=proxy-a.example.com:3128,proxy-b.example.com:3128
24
+
25
+ # ... with an explicit scheme and credentials:
26
+ #SCRAPER_PROXIES=http://user:pass@proxy.example.com:3128
27
+
28
+ # ... SOCKS (requires PySocks):
29
+ #SCRAPER_PROXIES=socks5://localhost:9050
30
+
31
+ # For a whole proxy farm, keep the list in its own file instead: one proxy per
32
+ # line, blank lines and "#" comments allowed. See `proxies.example.txt`.
33
+ # This scales to thousands of entries and can be regenerated by another tool
34
+ # without ever touching this file. Both settings may be combined.
35
+ #SCRAPER_PROXY_FILE=proxies.txt
36
+
37
+ # Leave both unset to crawl over a direct connection - that is the default.
38
+
39
+
40
+ # === Crawler tuning ========================================================
41
+
42
+ # Number of worker processes sharing the URL frontier.
43
+ #SCRAPER_THREADS=32
44
+
45
+ # Socket timeout per request, in seconds.
46
+ #SCRAPER_TIMEOUT=10.0
47
+
48
+ # Attempts per URL before it is given up on.
49
+ #SCRAPER_RETRIES=10
50
+
51
+ # Seed URL the crawl starts from. Any article URL on the site works.
52
+ #SCRAPER_START_URL=https://www.politico.eu/article/swedens-still-ahead-in-the-preparedness-game-and-now-it-means-business
scraping/README.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How this dataset was built
2
+
3
+ | File | Purpose |
4
+ |---|---|
5
+ | [`crawler.py`](./crawler.py) | Distributed whole-site crawler for `www.politico.eu`. Writes one JSON file per article to `pages/`. |
6
+ | [`finalize.ipynb`](./finalize.ipynb) | Merges `pages/*.json` into a single table, deduplicates it and pushes it to the Hub. |
7
+ | [`.env.example`](./.env.example) | Configuration template. Copy to `.env` and uncomment what you need. |
8
+ | [`proxies.example.txt`](./proxies.example.txt) | Proxy-list template for `SCRAPER_PROXY_FILE` — one proxy per line. |
9
+
10
+ ```bash
11
+ pip install mechanicalsoup beautifulsoup4 lxml python-dateutil fake-useragent \
12
+ pandas datasets huggingface_hub tqdm
13
+
14
+ python crawler.py # writes pages/*.json; `touch killall.txt` to stop
15
+ jupyter notebook finalize.ipynb
16
+ ```
17
+
18
+ ## Configuration
19
+
20
+ All settings are optional and are read from the environment or from a `.env`
21
+ file next to `crawler.py`. The defaults are exactly the values used for the
22
+ original crawl.
23
+
24
+ ```bash
25
+ cp .env.example .env # then uncomment what you need
26
+ ```
27
+
28
+ | Variable | Meaning |
29
+ |---|---|
30
+ | `SCRAPER_PROXIES` | Inline proxy pool — entries separated by commas, semicolons, spaces or newlines. |
31
+ | `SCRAPER_PROXY_FILE` | Path to a file with **one proxy per line** — the practical form for a proxy farm. |
32
+ | `SCRAPER_THREADS` | Number of worker processes sharing the URL frontier. |
33
+ | `SCRAPER_TIMEOUT` | Socket timeout per request, in seconds. |
34
+ | `SCRAPER_RETRIES` | Attempts per URL before giving up. |
35
+ | `SCRAPER_START_URL` | Seed URL the crawl starts from. |
36
+
37
+ Environment variables take precedence over `.env`, so a single run can be
38
+ overridden on the command line:
39
+
40
+ ```bash
41
+ SCRAPER_THREADS=4 python crawler.py
42
+ ```
43
+
44
+ ### Proxies
45
+
46
+ The original crawl ran behind a pool of forward proxies on a private network.
47
+ Those addresses have been removed from this published copy. A scheme is
48
+ optional on every entry (`http://` is assumed); one entry is picked per
49
+ request, so a pool spreads the load over several exits.
50
+
51
+ ```bash
52
+ # a single proxy
53
+ export SCRAPER_PROXIES="proxy-a.example.com:3128"
54
+
55
+ # a small pool, rotated per request
56
+ export SCRAPER_PROXIES="proxy-a.example.com:3128,proxy-b.example.com:3128"
57
+
58
+ # with an explicit scheme and credentials
59
+ export SCRAPER_PROXIES="http://user:pass@proxy.example.com:3128"
60
+
61
+ # SOCKS, if PySocks is installed
62
+ export SCRAPER_PROXIES="socks5://localhost:9050"
63
+ ```
64
+
65
+ For a **whole proxy farm**, keep the list in its own file — one proxy per line,
66
+ blank lines and `#` comments allowed — and point `SCRAPER_PROXY_FILE` at it.
67
+ The file can hold thousands of entries and be regenerated by another tool
68
+ without touching `.env` or the script:
69
+
70
+ ```bash
71
+ cp proxies.example.txt proxies.txt # then fill in your own entries
72
+ echo 'SCRAPER_PROXY_FILE=proxies.txt' >> .env
73
+ python crawler.py
74
+ ```
75
+
76
+ Leave both unset to crawl over a direct connection — that is the default and
77
+ what most of the crawls in this collection used.
78
+
79
+ The scripts contain no credentials, cookies or personal data.
80
+
81
+ Please crawl responsibly: honour `robots.txt` and the site's terms of use, keep
82
+ concurrency well below the 32 workers used here unless you have the operator's
83
+ permission, and prefer the published dataset over re-crawling.
scraping/crawler.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Whole-site crawler for www.politico.eu (POLITICO Europe).
3
+
4
+ This is the exact script that produced the Hugging Face dataset
5
+ https://huggingface.co/datasets/SinclairSchneider/politico_eu — see that dataset card for a
6
+ step-by-step description of the pipeline.
7
+
8
+ Overview
9
+ --------
10
+ * 32 worker processes share the URL frontier; a URL is routed to a worker by
11
+ ``int(md5(url).hexdigest(), 16) % 32`` so that no locking is required.
12
+ * The crawl is seeded with one article URL and discovers everything else by
13
+ following links below ``https://www.politico.eu/``.
14
+ * ``get_content()`` turns an article page into a record; pages with an empty
15
+ body are dropped. Each surviving article is written to
16
+ ``pages/<flattened-url>.json``.
17
+ * Known and visited URLs are appended to ``data/thread_<id>_pages*.txt``, so an
18
+ interrupted crawl resumes where it left off. Create a file named
19
+ ``killall.txt`` in the working directory to stop all workers cleanly.
20
+
21
+ Usage
22
+ -----
23
+ pip install mechanicalsoup beautifulsoup4 lxml python-dateutil fake-useragent
24
+ python crawler.py
25
+
26
+ Configuration
27
+ -------------
28
+ Copy ``.env.example`` to ``.env`` and uncomment what you need - proxies, worker
29
+ count, timeout, retries and the seed URL are all read from there (environment
30
+ variables still win over the file). For a large proxy farm put one proxy per
31
+ line into a text file and point ``SCRAPER_PROXY_FILE`` at it; see
32
+ ``proxies.example.txt``. The private proxy addresses used in the original crawl
33
+ have been removed from this published copy.
34
+
35
+ Please crawl responsibly: honour robots.txt and the site's terms of use, and
36
+ lower the worker count unless you have the operator's permission.
37
+ """
38
+
39
+ import hashlib
40
+ import multiprocessing
41
+ import mechanicalsoup
42
+
43
+ from bs4 import BeautifulSoup
44
+ import re
45
+ import json
46
+ import os
47
+ import io
48
+ import time
49
+ import random
50
+ from fake_useragent import UserAgent
51
+
52
+ from dateutil.parser import parse
53
+
54
+ base_url = "https://www.politico.eu/"
55
+
56
+ # --- Configuration ---------------------------------------------------------
57
+ # Every setting below can be supplied through the environment or through a
58
+ # ".env" file placed next to this script. Copy ".env.example" to ".env" and
59
+ # uncomment what you need:
60
+ #
61
+ # cp .env.example .env
62
+ #
63
+ # Nothing has to be set - the defaults are exactly the values that were used
64
+ # for the original crawl.
65
+ def _load_dotenv(path=".env"):
66
+ """Read a ".env" file: KEY=VALUE per line, "#" starts a comment.
67
+
68
+ Variables that are already set in the real environment win, so a single run
69
+ can still be overridden with e.g. ``SCRAPER_THREADS=4 python crawler.py``.
70
+ """
71
+ if not os.path.isfile(path):
72
+ return
73
+ with io.open(path, "r", encoding="utf-8") as handle:
74
+ for line in handle:
75
+ line = line.strip()
76
+ if not line or line.startswith("#") or "=" not in line:
77
+ continue
78
+ key, _, value = line.partition("=")
79
+ key = key.strip()
80
+ value = value.strip().strip('"').strip("'")
81
+ if key and key not in os.environ:
82
+ os.environ[key] = value
83
+
84
+
85
+ _load_dotenv()
86
+
87
+
88
+ def _load_proxy_pool():
89
+ """Build the proxy pool from SCRAPER_PROXIES and/or SCRAPER_PROXY_FILE.
90
+
91
+ SCRAPER_PROXIES inline list; entries separated by commas, semicolons,
92
+ spaces or newlines.
93
+ SCRAPER_PROXY_FILE path to a file holding one proxy per line, with blank
94
+ lines and "#" comments allowed. This is the practical
95
+ form for a whole proxy farm: the pool can be swapped or
96
+ regenerated without touching the script or the .env.
97
+
98
+ Both may be combined. Entries may be written with or without a scheme
99
+ ("http://" is assumed when none is given). Duplicates are dropped and an
100
+ empty pool simply means "connect directly".
101
+ """
102
+ raw = os.environ.get("SCRAPER_PROXIES", "")
103
+ proxy_file = os.environ.get("SCRAPER_PROXY_FILE", "").strip()
104
+ if proxy_file:
105
+ if not os.path.isfile(proxy_file):
106
+ raise SystemExit("SCRAPER_PROXY_FILE points to a missing file: " + proxy_file)
107
+ with io.open(proxy_file, "r", encoding="utf-8") as handle:
108
+ raw = raw + "\n" + handle.read()
109
+ cleaned = []
110
+ for line in raw.splitlines():
111
+ line = line.split("#", 1)[0].strip()
112
+ if line:
113
+ cleaned.append(line)
114
+ pool = []
115
+ for entry in re.split(r"[,;\s]+", " ".join(cleaned)):
116
+ entry = entry.strip()
117
+ if not entry:
118
+ continue
119
+ if "://" not in entry:
120
+ entry = "http://" + entry
121
+ if entry not in pool:
122
+ pool.append(entry)
123
+ return pool
124
+
125
+
126
+ PROXY_POOL = _load_proxy_pool()
127
+ NUM_THREADS = int(os.environ.get("SCRAPER_THREADS", "32"))
128
+ REQUEST_TIMEOUT = float(os.environ.get("SCRAPER_TIMEOUT", "10.0"))
129
+ MAX_RETRIES = int(os.environ.get("SCRAPER_RETRIES", "10"))
130
+ START_URL = os.environ.get("SCRAPER_START_URL", "https://www.politico.eu/article/swedens-still-ahead-in-the-preparedness-game-and-now-it-means-business")
131
+
132
+ def log(number, url):
133
+ if not os.path.isdir("log"):
134
+ os.mkdir("log")
135
+ with open("log"+os.sep+"thread_"+str(number)+".txt", "w") as f:
136
+ f.write(url)
137
+
138
+ def error(number, url):
139
+ if not os.path.isdir("error"):
140
+ os.mkdir("error")
141
+ with open("error"+os.sep+"thread_"+str(number)+".txt", "w") as f:
142
+ f.write(url)
143
+
144
+ def raw(number, url, page_str):
145
+ if not os.path.isdir("raw"):
146
+ os.mkdir("raw")
147
+ with open("raw"+os.sep+"thread_"+str(number)+".txt", "w") as f:
148
+ f.write(url)
149
+ f.write(page_str)
150
+
151
+ def get_content(url, page_str):
152
+ additional_attributes = {
153
+ 'author':'',
154
+ 'description':'',
155
+ 'keywords':'',
156
+ 'category':'',
157
+ 'countries':'',
158
+ 'dateCreated':'',
159
+ 'datePublished':'',
160
+ 'dateModified':'',
161
+ 'post_id':'',
162
+ 'url':'',
163
+ }
164
+ dict_return = {'content':'', 'title':'', 'additional_attributes': additional_attributes}
165
+
166
+ if page_str=="":
167
+ return dict_return
168
+
169
+ page_bs = BeautifulSoup(page_str, "lxml")
170
+
171
+ title = page_bs.find("meta", {'property':'og:title'}).get('content') if page_bs.find("meta", {'property':'og:title'}) != None else ""
172
+ content = " ".join([x.text.strip() for x in page_bs.find("article", {'class', 'article'}).find_all("p")]) if page_bs.find("article", {'class', 'article'}) != None else ""
173
+ author = json.loads(page_bs.find("script", {'type': 'application/ld+json'}).text).get('author', [{}]) if page_bs.find("script", {'type': 'application/ld+json'}) != None else ""
174
+ author = author[0].get('name', '') if len(author) > 0 else ""
175
+ description = json.loads(page_bs.find("script", {'type': 'application/ld+json'}).text).get('description', '') if page_bs.find("script", {'type': 'application/ld+json'}) != None else ""
176
+ keywords = json.loads(page_bs.find("script", {'type': 'application/ld+json'}).text).get('keywords', '') if page_bs.find("script", {'type': 'application/ld+json'}) != None else ""
177
+ category = json.loads(page_bs.find("script", {'type': 'application/ld+json'}).text).get('articleSection', '') if page_bs.find("script", {'type': 'application/ld+json'}) else ""
178
+ countries = [x.text.strip() for x in page_bs.find("div", {'class': 'tags__taxonomy--country'}).find_all("a")] if page_bs.find("div", {'class': 'tags__taxonomy--country'}) != None else []
179
+ dateCreated = json.loads(page_bs.find("script", {'type': 'application/ld+json'}).text).get('dateCreated', '') if page_bs.find("script", {'type': 'application/ld+json'}) else ""
180
+ datePublished = json.loads(page_bs.find("script", {'type': 'application/ld+json'}).text).get('datePublished', '') if page_bs.find("script", {'type': 'application/ld+json'}) else ""
181
+ dateModified = json.loads(page_bs.find("script", {'type': 'application/ld+json'}).text).get('dateModified', '') if page_bs.find("script", {'type': 'application/ld+json'}) else ""
182
+ post_id = json.loads(str(json.loads(page_bs.find("script", {'type': 'application/ld+json'}).text).get('custom_metadata', {}))).get('post_id') if page_bs.find("script", {'type': 'application/ld+json'}) != None else ""
183
+
184
+ additional_attributes = {
185
+ 'author':author,
186
+ 'description':description,
187
+ 'keywords':keywords,
188
+ 'category':category,
189
+ 'countries':countries,
190
+ 'dateCreated':dateCreated,
191
+ 'datePublished':datePublished,
192
+ 'dateModified':dateModified,
193
+ 'post_id':post_id,
194
+ 'url':url,
195
+ }
196
+ dict_return = {'content':content, 'title':title, 'additional_attributes': additional_attributes}
197
+ return dict_return
198
+
199
+ def get_urls(page_str):
200
+ return_urls = set()
201
+ page_bs = BeautifulSoup(page_str, "lxml")
202
+ for tag in page_bs.findAll("a", href=True):
203
+ url = tag.get("href", '')
204
+ if "#" in url:
205
+ continue
206
+ if url.startswith(base_url):
207
+ return_urls.add(url)
208
+ if url.startswith("/"):
209
+ url = base_url + url
210
+ return_urls.add(url)
211
+ return return_urls
212
+
213
+ def readSavedData(iId, sPageset, sPagesetVisited):
214
+ if not os.path.isdir("data"):
215
+ os.mkdir("data")
216
+ if os.path.isfile("data/thread_"+str(iId)+"_pages.txt"):
217
+ with io.open("data/thread_"+str(iId)+"_pages.txt", "r", encoding="utf-8") as f:
218
+ for line in f:
219
+ if "#" in line:
220
+ continue
221
+ line = line.replace("\n", "")
222
+ if line != "":
223
+ sPageset.add(line)
224
+
225
+ if os.path.isfile("data/thread_"+str(iId)+"_pages_visited.txt"):
226
+ with io.open("data/thread_"+str(iId)+"_pages_visited.txt", "r", encoding="utf-8") as f:
227
+ for line in f:
228
+ if "#" in line:
229
+ continue
230
+ line = line.replace("\n", "")
231
+ if line != "":
232
+ sPagesetVisited.add(line)
233
+
234
+ def addStartChannel(sPage, iNumberOfThreads, lQueues):
235
+ iIndex = int(hashlib.md5(sPage.encode("utf")).hexdigest(),16)%iNumberOfThreads
236
+ lQueues[iIndex].put(sPage)
237
+
238
+ def getNextPage(lQueues, iId, sPageset, sPagesetVisited):
239
+ while True:
240
+ if os.path.isfile("killall.txt"):
241
+ return None
242
+
243
+ while not lQueues[iId].empty():
244
+ sPage = lQueues[iId].get()
245
+ iLenBefore = len(sPageset)
246
+ sPageset.add(sPage)
247
+ iLenAfter = len(sPageset)
248
+ if iLenBefore != iLenAfter:
249
+ with io.open("data/thread_"+str(iId)+"_pages.txt", "a", encoding="utf-8") as f:
250
+ if sPage != "" and sPage != "\t":
251
+ f.write(sPage + "\n")
252
+ sPagesetToVisit = sPageset - sPagesetVisited
253
+
254
+ if len(sPagesetToVisit) != 0:
255
+ sPage = list(sPagesetToVisit)[0]
256
+ return sPage
257
+ else:
258
+ print("Thread " + str(iId) + " is waiting")
259
+ time.sleep(3)
260
+
261
+ def addPagesToVisit(sPages, iNumberOfThreads, lQueues):
262
+ for sPage in sPages:
263
+ if sPage != "":
264
+ iIndex = int(hashlib.md5(sPage.encode("utf")).hexdigest(), 16) % iNumberOfThreads
265
+ lQueues[iIndex].put(sPage)
266
+
267
+ def addVisitedPages(sPage, sPagesetsetVisited, iId):
268
+ iLenBefore = len(sPagesetsetVisited)
269
+ sPagesetsetVisited.add(sPage)
270
+ iLenAfter = len(sPagesetsetVisited)
271
+ if iLenBefore != iLenAfter:
272
+ with io.open("data/thread_"+str(iId)+"_pages_visited.txt", "a", encoding="utf-8") as f:
273
+ if sPage != "":
274
+ f.write(sPage+"\n")
275
+
276
+ def crawler(iId, iNumberOfThreads, lQueues):
277
+ sPageset = set()
278
+ sPagesetVisited = set()
279
+ readSavedData(iId, sPageset, sPagesetVisited)
280
+
281
+ while True:
282
+ sPage = getNextPage(lQueues, iId, sPageset, sPagesetVisited)
283
+ if sPage is None:
284
+ break
285
+ if "#" in sPage:
286
+ continue
287
+
288
+ if (not "/files/" in sPage) and \
289
+ (not "/video/" in sPage) and \
290
+ (not ".jpg" in sPage) and \
291
+ (not ".pdf" in sPage) and \
292
+ (not ".xml" in sPage) and \
293
+ (not ".pptx" in sPage) and \
294
+ (not ".shtml" in sPage) and \
295
+ len(sPage.split('/')) > 4 and \
296
+ (not ".epub" in sPage):
297
+
298
+ log(iId, sPage)
299
+ for i in range(MAX_RETRIES):
300
+ try:
301
+ lproxies = PROXY_POOL
302
+ proxy = lproxies[int((int(time.time())/1))%len(lproxies)] if lproxies else None
303
+ proxy = lproxies[int(iId)%len(lproxies)] if lproxies else None
304
+ proxies = {'https': proxy, 'http': proxy} if proxy else {}
305
+ browser = mechanicalsoup.StatefulBrowser()
306
+ ua = UserAgent()
307
+ browser.set_user_agent(ua.random)
308
+ browser.session.proxies = proxies
309
+
310
+
311
+ browser.open(sPage, timeout=REQUEST_TIMEOUT)
312
+ page = browser.get_current_page()
313
+ page_str = str(page)
314
+ if "#challenge-error-text" in page_str:
315
+ print("error, we will wait a moment and continue")
316
+ time.sleep(1)
317
+ continue
318
+ if "You don't have permission to access" in page_str:
319
+ print("error, we will wait a moment and continue")
320
+ time.sleep(1)
321
+ continue
322
+ raw(iId, sPage, page_str)
323
+ break
324
+ except:
325
+ print(sPage)
326
+ print("retry")
327
+ browser.close()
328
+ continue
329
+
330
+ browser.close()
331
+ else:
332
+ page_str = ""
333
+
334
+ try:
335
+ content = get_content(sPage, page_str)
336
+ except:
337
+ error(iId, sPage)
338
+
339
+ if content['content'] != '':
340
+ file_path = sPage.replace(base_url+"/", "").replace("/", "_")[-200:]
341
+ file_path = "pages/"+file_path
342
+ file_path = file_path[:-1] if file_path.endswith("_") else file_path
343
+ file_path = file_path+".json"
344
+ content_json = json.dumps(content)
345
+ with open(file_path, "w", encoding = "utf-8") as f:
346
+ f.write(content_json)
347
+ else:
348
+ pass
349
+
350
+ sPages = get_urls(page_str)
351
+ addPagesToVisit(sPages, iNumberOfThreads, lQueues)
352
+ addVisitedPages(sPage, sPagesetVisited, iId)
353
+
354
+ print("Thread: " + str(iId) + " chanels visited: " + str(len(sPagesetVisited)) + " channels to visit: " + str(len(sPageset - sPagesetVisited)))
355
+
356
+ def main():
357
+ if not os.path.isdir("pages"):
358
+ os.mkdir("pages")
359
+
360
+ iNumberOfThreads = NUM_THREADS
361
+ lQueues = []
362
+ mgr = multiprocessing.Manager()
363
+ for i in range(iNumberOfThreads):
364
+ qQueue = mgr.Queue()
365
+ lQueues.append(qQueue)
366
+
367
+ lIds = range(0, iNumberOfThreads)
368
+ lNumberOfThreads = [iNumberOfThreads] * iNumberOfThreads
369
+ llQueues = [lQueues] * iNumberOfThreads
370
+ addStartChannel(START_URL, iNumberOfThreads, lQueues)
371
+ lArguments = list(zip(lIds, lNumberOfThreads, llQueues))
372
+ with multiprocessing.Pool(processes=iNumberOfThreads) as pool:
373
+ pool.starmap(crawler, lArguments)
374
+
375
+ if __name__ == "__main__":
376
+ main()
scraping/finalize.ipynb ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# `POLITICO Europe (politico.eu)` — consolidation notebook\n",
8
+ "\n",
9
+ "This notebook is the second half of the pipeline behind\n",
10
+ "[`SinclairSchneider/politico_eu`](https://huggingface.co/datasets/SinclairSchneider/politico_eu).\n",
11
+ "\n",
12
+ "`crawler.py` writes one JSON file per article into `pages/`. This notebook\n",
13
+ "\n",
14
+ "1. reads every `pages/*.json`,\n",
15
+ "2. flattens the nested records into one `pandas` column per field,\n",
16
+ "3. drops duplicate articles by headline (`drop_duplicates(subset=['title'])`),\n",
17
+ "4. writes `politico_eu.json` and pushes the result to the Hugging Face Hub.\n",
18
+ "\n",
19
+ "Outputs have been cleared before publication.\n",
20
+ ""
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": null,
26
+ "metadata": {},
27
+ "outputs": [],
28
+ "source": [
29
+ "import glob\n",
30
+ "import json\n",
31
+ "import pandas as pd\n",
32
+ "from datasets import Dataset\n",
33
+ "import huggingface_hub\n",
34
+ "from dateutil.parser import parse\n",
35
+ "from tqdm import tqdm"
36
+ ]
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "execution_count": null,
41
+ "metadata": {},
42
+ "outputs": [],
43
+ "source": [
44
+ "with open(\"pages/ylvie-goulard-cleared-from-charges-that-could-have-costed-her-commissioner-job-commission-candidate-sylvie-goulard-cleared-from-embezzlement-charges-emmanuel-macron-european-commission-presidency-thi.json\", \"r\", encoding=\"utf-8\") as f:\n",
45
+ " json_input = f.read()\n",
46
+ " dict_input_example = json.loads(json_input)"
47
+ ]
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "execution_count": null,
52
+ "metadata": {},
53
+ "outputs": [],
54
+ "source": [
55
+ "dict_input_example"
56
+ ]
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "execution_count": null,
61
+ "metadata": {},
62
+ "outputs": [],
63
+ "source": [
64
+ "json_files = glob.glob(\"pages/*.json\")\n",
65
+ "len(json_files)"
66
+ ]
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "execution_count": null,
71
+ "metadata": {},
72
+ "outputs": [],
73
+ "source": [
74
+ "title = []\n",
75
+ "content = []\n",
76
+ "author = []\n",
77
+ "description = []\n",
78
+ "keywords = []\n",
79
+ "category = []\n",
80
+ "countries = []\n",
81
+ "dateCreated = []\n",
82
+ "datePublished = []\n",
83
+ "dateModified = []\n",
84
+ "post_id = []\n",
85
+ "url = []\n",
86
+ "for file in tqdm(json_files):\n",
87
+ " with open(file, \"r\") as f:\n",
88
+ " d = json.loads(f.read())\n",
89
+ " title.append(d['title'])\n",
90
+ " content.append(d['content'])\n",
91
+ " author.append(d['additional_attributes']['author'])\n",
92
+ " description.append(d['additional_attributes']['description'])\n",
93
+ " keywords.append(d['additional_attributes']['keywords'])\n",
94
+ " category.append(d['additional_attributes']['category'])\n",
95
+ " countries.append(d['additional_attributes']['countries'])\n",
96
+ " dateCreated.append(d['additional_attributes']['dateCreated'])\n",
97
+ " datePublished.append(d['additional_attributes']['datePublished'])\n",
98
+ " dateModified.append(d['additional_attributes']['dateModified'])\n",
99
+ " post_id.append(d['additional_attributes']['post_id'])\n",
100
+ " url.append(d['additional_attributes']['url'])"
101
+ ]
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "execution_count": null,
106
+ "metadata": {},
107
+ "outputs": [],
108
+ "source": [
109
+ "df = pd.DataFrame(\n",
110
+ " {\n",
111
+ " 'title':title,\n",
112
+ " 'content':content,\n",
113
+ " 'author':author,\n",
114
+ " 'description':description,\n",
115
+ " 'keywords':keywords,\n",
116
+ " 'category':category,\n",
117
+ " 'countries':countries,\n",
118
+ " 'dateCreated':dateCreated,\n",
119
+ " 'datePublished':datePublished,\n",
120
+ " 'dateModified':dateModified,\n",
121
+ " 'post_id':post_id,\n",
122
+ " 'url':url,\n",
123
+ " }\n",
124
+ ")"
125
+ ]
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "execution_count": null,
130
+ "metadata": {},
131
+ "outputs": [],
132
+ "source": [
133
+ "df['keywords']"
134
+ ]
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "execution_count": null,
139
+ "metadata": {},
140
+ "outputs": [],
141
+ "source": [
142
+ "df = df.drop_duplicates(subset=['title'])"
143
+ ]
144
+ },
145
+ {
146
+ "cell_type": "code",
147
+ "execution_count": null,
148
+ "metadata": {},
149
+ "outputs": [],
150
+ "source": [
151
+ "df = df[df['datePublished']!=\"\"]"
152
+ ]
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "execution_count": null,
157
+ "metadata": {},
158
+ "outputs": [],
159
+ "source": [
160
+ "df = df.sort_values(by=['datePublished'], ascending=False).reset_index(drop=True)"
161
+ ]
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "execution_count": null,
166
+ "metadata": {},
167
+ "outputs": [],
168
+ "source": [
169
+ "df"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "execution_count": null,
175
+ "metadata": {},
176
+ "outputs": [],
177
+ "source": [
178
+ "df.to_json(\"politico_eu.json\")"
179
+ ]
180
+ },
181
+ {
182
+ "cell_type": "code",
183
+ "execution_count": null,
184
+ "metadata": {},
185
+ "outputs": [],
186
+ "source": [
187
+ "ds = Dataset.from_pandas(df)"
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "execution_count": null,
193
+ "metadata": {},
194
+ "outputs": [],
195
+ "source": [
196
+ "ds.push_to_hub(\"SinclairSchneider/politico_eu\")"
197
+ ]
198
+ },
199
+ {
200
+ "cell_type": "code",
201
+ "execution_count": null,
202
+ "metadata": {},
203
+ "outputs": [],
204
+ "source": [
205
+ "ds.push_to_hub(\"NLP-UniBW/politico_eu\")"
206
+ ]
207
+ }
208
+ ],
209
+ "metadata": {
210
+ "kernelspec": {
211
+ "display_name": "Python 3",
212
+ "language": "python",
213
+ "name": "python3"
214
+ },
215
+ "language_info": {
216
+ "name": "python"
217
+ }
218
+ },
219
+ "nbformat": 4,
220
+ "nbformat_minor": 5
221
+ }
scraping/proxies.example.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # One proxy per line. Blank lines and "#" comments are ignored.
2
+ # A scheme is optional - "http://" is assumed when none is given.
3
+ #
4
+ # Copy this file (e.g. to `proxies.txt`), fill in your own entries and point
5
+ # SCRAPER_PROXY_FILE at it:
6
+ #
7
+ # SCRAPER_PROXY_FILE=proxies.txt
8
+ #
9
+ # This is the convenient form for a large proxy farm - the file can hold
10
+ # thousands of lines and be regenerated by another tool at any time.
11
+
12
+ proxy-a.example.com:3128
13
+ proxy-b.example.com:3128
14
+ http://user:pass@proxy-c.example.com:3128
15
+ socks5://localhost:9050