euractiv_com / scraping /crawler.py
SinclairSchneider's picture
Add detailed dataset card and the scraping pipeline used to build it
1603727 verified
Raw History Blame Contribute Delete
14.1 kB
"""
Whole-site crawler for www.euractiv.com (Euractiv).
This is the crawler script behind the Hugging Face dataset
https://huggingface.co/datasets/SinclairSchneider/euractiv_com - see that dataset card for a
step-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 by
following links (see ``get_urls()``).
* Pages are not fetched directly: each URL is POSTed as ``{"url": ...}`` to an
HTML-rendering service, which must answer ``{"html": "<page source>"}``.
Set ``SCRAPER_RENDER_URL`` to such a service; the private address used for
the original crawl has been removed from this published copy.
* ``get_content()`` turns an article page into a record; pages with an empty
body 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 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 requests beautifulsoup4 lxml python-dateutil mechanicalsoup fake-useragent
SCRAPER_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 (environment
variables still win over the file).
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
import random
from fake_useragent import UserAgent
import requests
from dateutil.parser import parse
base_url = "https://www.euractiv.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.
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()
# 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://www.euractiv.com/news/exclusive-eu-parliament-paid-thousands-to-greek-neo-nazi-mep-after-criminal-conviction/")
# seconds per call to the rendering service; unset = wait indefinitely, as in the original crawl
REQUEST_TIMEOUT = float(os.environ["SCRAPER_TIMEOUT"]) if os.environ.get("SCRAPER_TIMEOUT", "").strip() else None
def log(number, url):
if not os.path.isdir("log"):
os.mkdir("log")
with open("log"+os.sep+"thread_"+str(number)+".txt", "w") as f:
f.write(url)
def error(number, url):
if not os.path.isdir("error"):
os.mkdir("error")
with open("error"+os.sep+"thread_"+str(number)+".txt", "w") as f:
f.write(url)
def raw(number, url, page_str):
if not os.path.isdir("raw"):
os.mkdir("raw")
with open("raw"+os.sep+"thread_"+str(number)+".txt", "w") as f:
f.write(url)
f.write(page_str)
def get_content(url, page_str):
additional_attributes = {
'author':'',
'description':'',
'keywords':'',
'category':'',
'datePublished':'',
'dateModified':'',
'language':'',
'url':'',
}
dict_return = {'content':'', 'title':'', 'additional_attributes': additional_attributes}
if page_str=="":
return dict_return
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 False
if pro_article == True:
return dict_return
title = page_bs.find("meta", {'property':'og:title'}).get('content', '').replace(" | Euractiv", "") if page_bs.find("meta", {'property':'og:title'}) != None else ""
content = " ".join([x.text.strip() for x in page_bs.find("article", {'class':'c-news-detail'}).find_all('p')]) if page_bs.find("article", {'class':'c-news-detail'}) != None else ""
author = page_bs.find("a", {'rel': 'author'}).text.strip() if page_bs.find("a", {'rel': 'author'}) != None else ""
description = page_bs.find("meta", {'property':'og:description'}).get('content', '') if page_bs.find("meta", {'property':'og:description'}) != None else ""
keywords = [x.text.strip() for x in page_bs.find("div", {'class':'c-news-detail__footer-tags'}).find_all('a')] if page_bs.find("div", {'class':'c-news-detail__footer-tags'}) != None else []
category = page_bs.find("a", {'rel': 'section'}).text.strip() if page_bs.find("a", {'rel': 'section'}) != None else ""
datePublished = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('@graph', [{}])[0].get('datePublished', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else ""
dateModified = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('@graph', [{}])[0].get('dateModified', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else ""
language = json.loads(page_bs.find("script", {'type':'application/ld+json'}).text).get('@graph', [{}])[0].get('inLanguage', '') if page_bs.find("script", {'type':'application/ld+json'}) != None else ""
additional_attributes = {
'author':author,
'description':description,
'keywords':keywords,
'category':category,
'datePublished':datePublished,
'dateModified':dateModified,
'language':language,
'url':url,
}
dict_return = {'content':content, 'title':title, 'additional_attributes': additional_attributes}
return dict_return
def 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:
continue
if url.startswith(base_url):
return_urls.add(url)
if url.startswith("/"):
url = base_url + url
return_urls.add(url)
return return_urls
except:
return set()
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:
content = None
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 ".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 False
if pro_article == True:
print("pay article")
break
try:
content = get_content(sPage, page_str)
except:
error(iId, sPage)
if content['content'] != '':
break
else:
print("content==\"\" retry "+str(9-i)+" times.")
except:
print(sPage)
print("retry")
continue
else:
page_str = ""
if content == None:
content = {'content':''}
page_str = ""
if content['content'] != '':
file_path = sPage.replace(base_url+"/", "").replace("/", "_")[-200:]
file_path = "pages/"+file_path
file_path = file_path[:-1] if file_path.endswith("_") else file_path
file_path = file_path+".json"
content_json = json.dumps(content)
with open(file_path, "w", encoding = "utf-8") as f:
f.write(content_json)
else:
pass
if 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")
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()