focus_de / scraping /crawler.py
SinclairSchneider's picture
Add detailed dataset card and the scraping pipeline used to build it
5bf8f7f verified
Raw History Blame Contribute Delete
13.7 kB
"""
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()