File size: 13,680 Bytes
5bf8f7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
"""
Whole-site crawler for www.focus.de (FOCUS online).

This is the exact script that produced the Hugging Face dataset
https://huggingface.co/datasets/SinclairSchneider/focus_de — see that dataset card for a
step-by-step description of the pipeline.

Overview
--------
* 32 worker processes share the URL frontier; a URL is routed to a worker by
  ``int(md5(url).hexdigest(), 16) % 32`` so that no locking is required.
* The crawl is seeded with one article URL and discovers everything else by
  following links below ``https://www.focus.de/``.
* ``get_content()`` turns an article page into a record; pages without a ``div.displayDate`` element
  (i.e. non-article pages) are dropped. Each surviving article is written to
  ``pages/<flattened-url>.json``.
* Known and visited URLs are appended to ``data/thread_<id>_pages*.txt``, so an
  interrupted crawl resumes where it left off. Create a file named
  ``killall.txt`` in the working directory to stop all workers cleanly.

Usage
-----
    pip install mechanicalsoup beautifulsoup4 lxml python-dateutil fake-useragent
    python crawler.py

Configuration
-------------
Copy ``.env.example`` to ``.env`` and uncomment what you need - proxies, worker
count, timeout, retries and the seed URL are all read from there (environment
variables still win over the file). For a large proxy farm put one proxy per
line into a text file and point ``SCRAPER_PROXY_FILE`` at it; see
``proxies.example.txt``. The original crawl connected
directly, without proxies.

Please crawl responsibly: honour robots.txt and the site's terms of use, and
lower the worker count unless you have the operator's permission.
"""

import hashlib
import multiprocessing
import mechanicalsoup

from bs4 import BeautifulSoup
import re
import json
import os
import io
import time

from dateutil.parser import parse

base_url = "https://www.focus.de/"

# --- Configuration ---------------------------------------------------------
# Every setting below can be supplied through the environment or through a
# ".env" file placed next to this script.  Copy ".env.example" to ".env" and
# uncomment what you need:
#
#     cp .env.example .env
#
# Nothing has to be set - the defaults are exactly the values that were used
# for the original crawl.
def _load_dotenv(path=".env"):
    """Read a ".env" file: KEY=VALUE per line, "#" starts a comment.

    Variables that are already set in the real environment win, so a single run
    can still be overridden with e.g. ``SCRAPER_THREADS=4 python crawler.py``.
    """
    if not os.path.isfile(path):
        return
    with io.open(path, "r", encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            key, _, value = line.partition("=")
            key = key.strip()
            value = value.strip().strip('"').strip("'")
            if key and key not in os.environ:
                os.environ[key] = value


_load_dotenv()


def _load_proxy_pool():
    """Build the proxy pool from SCRAPER_PROXIES and/or SCRAPER_PROXY_FILE.

    SCRAPER_PROXIES     inline list; entries separated by commas, semicolons,
                        spaces or newlines.
    SCRAPER_PROXY_FILE  path to a file holding one proxy per line, with blank
                        lines and "#" comments allowed.  This is the practical
                        form for a whole proxy farm: the pool can be swapped or
                        regenerated without touching the script or the .env.

    Both may be combined.  Entries may be written with or without a scheme
    ("http://" is assumed when none is given).  Duplicates are dropped and an
    empty pool simply means "connect directly".
    """
    raw = os.environ.get("SCRAPER_PROXIES", "")
    proxy_file = os.environ.get("SCRAPER_PROXY_FILE", "").strip()
    if proxy_file:
        if not os.path.isfile(proxy_file):
            raise SystemExit("SCRAPER_PROXY_FILE points to a missing file: " + proxy_file)
        with io.open(proxy_file, "r", encoding="utf-8") as handle:
            raw = raw + "\n" + handle.read()
    cleaned = []
    for line in raw.splitlines():
        line = line.split("#", 1)[0].strip()
        if line:
            cleaned.append(line)
    pool = []
    for entry in re.split(r"[,;\s]+", " ".join(cleaned)):
        entry = entry.strip()
        if not entry:
            continue
        if "://" not in entry:
            entry = "http://" + entry
        if entry not in pool:
            pool.append(entry)
    return pool


PROXY_POOL = _load_proxy_pool()
NUM_THREADS = int(os.environ.get("SCRAPER_THREADS", "32"))
REQUEST_TIMEOUT = float(os.environ.get("SCRAPER_TIMEOUT", "10.0"))
MAX_RETRIES = int(os.environ.get("SCRAPER_RETRIES", "1000"))
START_URL = os.environ.get("SCRAPER_START_URL", "https://www.focus.de/kaufberatung/deals_angebote/ice-guenstiger-als-regionalbahn-die-bahn-lockt-mit-ice-tickets-fuer-9-90-euro-das-muessen-sie-beachten_id_178649661.html")

def get_content(page_str):
    content = ""
    title = ""
    category = ""
    is_article = False
    author = ""
    description = ""
    date_published_time_at = ""
    additional_attributes = {}
    
    page_bs = BeautifulSoup(page_str, "lxml")
    if page_bs.find("div", {"class": "displayDate"}):
        is_article = True
    
    if page_bs.find("link", {"rel": "canonical"}):
        link = page_bs.find("link", {"rel": "canonical"}).attrs.get('href', '')
        if "www.focus.de/politik/" in link: 
            category="politik"
        elif "www.focus.de/finanzen/" in link:
            category="finanzen"
        elif "www.focus.de/perspektiven/" in link:
            category="perspektiven"
        elif "www.focus.de/earth/" in link:
            category="earth"
        elif "www.focus.de/wissen/" in link:
            category="wissen"
        elif "www.focus.de/gesundheit/" in link:
            category="gesundheit"
        elif "www.focus.de/kultur/" in link:
            category="kultur"
        elif "www.focus.de/panorama/" in link:
            category="panorama"
        elif "www.focus.de/sport/" in link:
            category="sport"
        elif "www.focus.de/reisen/" in link:
            category="reisen"
        elif "www.focus.de/auto/" in link:
            category="auto"
        elif "www.focus.de/immobilien/" in link:
            category="immobilien"
        elif "www.focus.de/kaufberatung/" in link:
            category="kaufberatung"
        elif "www.focus.de/experts/" in link:
            category="experts"
        elif "www.focus.de/deals/" in link:
            category="deals"
        elif "www.focus.de/digital/" in link:
            category="digital"
        elif "www.focus.de/familie" in link:
            category="familie"
        elif "www.focus.de/familie" in link:
            category="familie"
    
    if page_bs.find("div", {"class": "articleContent"}):
        content_raw = page_bs.find("div", {"class": "articleContent"})
        if content_raw.find("div", {"class": "article-social-border"}):
            content_raw.find("div", {"class": "article-social-border"}).decompose()
        if content_raw.find("div", {"class": "affiliate_info"}):
            content_raw.find("div", {"class": "affiliate_info"}).decompose()
    
        content = re.sub('\n{3,}', '\n\n', content_raw.get_text().replace("\t", "").strip())
        content = re.sub(' {2,}', ' ', content).replace("\n ", "\n")
    if page_bs.find("title"):
        title = page_bs.find("title").get_text()
    if page_bs.find("meta", {"name": "author"}):
        author = page_bs.find("meta", {"name": "author"}).attrs.get('content', '')
    if page_bs.find("meta", {"name": "description"}):
        description = page_bs.find("meta", {"name": "description"}).attrs.get('content', '')
    if page_bs.find("meta", {"name": "date"}):
        date_published_time_at = page_bs.find("meta", {"name": "date"}).attrs.get('content', '')
    
    additional_attributes = {'is_article':is_article, 'category': category, 'author':author, 'description':description, 'date_published_time_at':date_published_time_at}
    dict_return = {'content':content, 'title':title, 'additional_attributes': additional_attributes}
    return dict_return
    
def get_urls(page_str):
    return_urls = set()
    page_bs = BeautifulSoup(page_str, "lxml")
    for tag in page_bs.findAll("a", href=True):
        url = tag.get("href", '')
        if "#" in url:
            continue
        if url.startswith(base_url):
            return_urls.add(url)
        if url.startswith("/"):
            url = base_url + url
            return_urls.add(url)
    return return_urls

def readSavedData(iId, sPageset, sPagesetVisited):
    if not os.path.isdir("data"):
        os.mkdir("data")
    if os.path.isfile("data/thread_"+str(iId)+"_pages.txt"):
        with io.open("data/thread_"+str(iId)+"_pages.txt", "r", encoding="utf-8") as f:
            for line in f:
                if "#" in line:
                    continue
                line = line.replace("\n", "")
                if line != "":
                    sPageset.add(line)

    if os.path.isfile("data/thread_"+str(iId)+"_pages_visited.txt"):
        with io.open("data/thread_"+str(iId)+"_pages_visited.txt", "r", encoding="utf-8") as f:
            for line in f:
                if "#" in line:
                    continue
                line = line.replace("\n", "")
                if line != "":
                    sPagesetVisited.add(line)

def addStartChannel(sPage, iNumberOfThreads, lQueues):
    iIndex = int(hashlib.md5(sPage.encode("utf")).hexdigest(),16)%iNumberOfThreads
    lQueues[iIndex].put(sPage)

def getNextPage(lQueues, iId, sPageset, sPagesetVisited):
    while True:
        if os.path.isfile("killall.txt"):
            return None

        while not lQueues[iId].empty():
            sPage = lQueues[iId].get()
            iLenBefore = len(sPageset)
            sPageset.add(sPage)
            iLenAfter = len(sPageset)
            if iLenBefore != iLenAfter:
                with io.open("data/thread_"+str(iId)+"_pages.txt", "a", encoding="utf-8") as f:
                    if sPage != "" and sPage != "\t":
                        f.write(sPage + "\n")
        sPagesetToVisit = sPageset - sPagesetVisited

        if len(sPagesetToVisit) != 0:
            sPage = list(sPagesetToVisit)[0]
            return sPage
        else:
            print("Thread " + str(iId) + " is waiting")
            time.sleep(3)

def addPagesToVisit(sPages, iNumberOfThreads, lQueues):
    for sPage in sPages:
        if sPage != "":
            iIndex = int(hashlib.md5(sPage.encode("utf")).hexdigest(), 16) % iNumberOfThreads
            lQueues[iIndex].put(sPage)

def addVisitedPages(sPage, sPagesetsetVisited, iId):
    iLenBefore = len(sPagesetsetVisited)
    sPagesetsetVisited.add(sPage)
    iLenAfter = len(sPagesetsetVisited)
    if iLenBefore != iLenAfter:
        with io.open("data/thread_"+str(iId)+"_pages_visited.txt", "a", encoding="utf-8") as f:
            if sPage != "":
                f.write(sPage+"\n")

def crawler(iId, iNumberOfThreads, lQueues):
    sPageset = set()
    sPagesetVisited = set()
    readSavedData(iId, sPageset, sPagesetVisited)

    while True:
        sPage = getNextPage(lQueues, iId, sPageset, sPagesetVisited)
        if sPage is None:
            break
        if "#" in sPage:
            continue

        if (not "/files/" in sPage) and (not "/video/" in sPage) and (not ".jpg" in sPage) and (not ".pdf" in sPage) and (not ".epub" in sPage):
            for i in range(MAX_RETRIES):
                try:
                    browser = mechanicalsoup.StatefulBrowser()
                    browser.open(sPage, timeout=REQUEST_TIMEOUT)
                    page = browser.get_current_page()
                    page_str = str(page)
                    break
                except:
                    print(sPage)
                    print("retry")
                    browser.close()
                    continue
                    
            browser.close()
        else:
            page_str = ""

        content = get_content(page_str)
        if content['additional_attributes']['is_article'] == True:
            file_path = sPage.replace(base_url+"/", "").replace("/", "_")[-200:]
            file_path = "pages/"+file_path
            file_path = file_path[:-1] if file_path.endswith("_") else file_path
            file_path = file_path+".json"
            content_json = json.dumps(content)
            with open(file_path, "w", encoding = "utf-8") as f:
                f.write(content_json)
        else:
            pass

        sPages = get_urls(page_str)
        addPagesToVisit(sPages, iNumberOfThreads, lQueues)
        addVisitedPages(sPage, sPagesetVisited, iId)

        print("Thread: " + str(iId) + " chanels visited: " + str(len(sPagesetVisited)) + " channels to visit: " + str(len(sPageset - sPagesetVisited)))

def main():
    if not os.path.isdir("pages"):
        os.mkdir("pages")

    iNumberOfThreads = NUM_THREADS
    lQueues = []
    mgr = multiprocessing.Manager()
    for i in range(iNumberOfThreads):
        qQueue = mgr.Queue()
        lQueues.append(qQueue)

    lIds = range(0, iNumberOfThreads)
    lNumberOfThreads = [iNumberOfThreads] * iNumberOfThreads
    llQueues = [lQueues] * iNumberOfThreads
    addStartChannel(START_URL, iNumberOfThreads, lQueues)
    lArguments = list(zip(lIds, lNumberOfThreads, llQueues))
    with multiprocessing.Pool(processes=iNumberOfThreads) as pool:
        pool.starmap(crawler, lArguments)

if __name__ == "__main__":
    main()