Merge branch 'job-bund-topic-matching' into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
2026-07-14 16:36:39 +02:00
20 changed files with 3020 additions and 1 deletions
@@ -0,0 +1,12 @@
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class AktuellItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
@@ -0,0 +1,103 @@
# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
class AktuellSpiderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, or item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Request or item objects.
pass
def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info("Spider opened: %s" % spider.name)
class AktuellDownloaderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info("Spider opened: %s" % spider.name)
@@ -0,0 +1,13 @@
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class AktuellPipeline:
def process_item(self, item, spider):
return item
@@ -0,0 +1,93 @@
# Scrapy settings for aktuell project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = "aktuell"
SPIDER_MODULES = ["aktuell.spiders"]
NEWSPIDER_MODULE = "aktuell.spiders"
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = "aktuell (+http://www.yourdomain.com)"
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 5
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
# "Accept-Language": "en",
#}
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# "aktuell.middlewares.AktuellSpiderMiddleware": 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# "aktuell.middlewares.AktuellDownloaderMiddleware": 543,
#}
# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# "scrapy.extensions.telnet.TelnetConsole": None,
#}
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# "aktuell.pipelines.AktuellPipeline": 300,
#}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = "httpcache"
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = "scrapy.extensions.httpcache.FilesystemCacheStorage"
# Set settings whose default value is deprecated to a future-proof value
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEED_EXPORT_ENCODING = "utf-8"
@@ -0,0 +1,4 @@
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
@@ -0,0 +1,45 @@
import scrapy
class LinksCrawler(scrapy.Spider):
name = "aktuell-links"
current = 1
first = True
max_num = 100
def start_requests(self):
url = 'https://www.uni-due.de/aktuell/?page=1&list_max=250'
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
if self.first:
self.first = False
max_num_text = response.selector.xpath('//div[contains(@id,"content__old__main")]/form/div/div/div[1]/div[1]/text()[2]').get()
self.max_num = int(max_num_text[4:])
rows = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")]').getall()
for i in range(len(rows)):
cols = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div').getall()
for o in range(len(cols)):
link = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div[' + str(o + 1) + ']/div/a/@href').get()
tags_num = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div[' + str(o + 1) + ']/div/ul/li').getall()
tags = []
for p in range(len(tags_num)):
tag = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div[' + str(o + 1) + ']/div/ul/li[' + str(p + 1) + ']/a/text()').get()
if tag != None:
tags.append(tag)
yield {
"link": "https://www.uni-due.de" + link,
"tags": tags
}
self.current = self.current + 1
if self.current <= self.max_num:
next_page = "https://www.uni-due.de/aktuell/?page=" + str(self.current) + "&list_max=250"
yield response.follow(next_page, callback=self.parse)
@@ -0,0 +1,153 @@
import scrapy
import json
from scrapy.linkextractors import LinkExtractor
import os
class MetaDataCrawler(scrapy.Spider):
name = "aktuell-metadata"
link_extractor = LinkExtractor()
log = {}
def start_requests(self):
with open("out/links.json", "r") as file:
urls = json.load(file)
print("file loaded")
print("start logging")
# start log
if os.path.exists("out/aktuell_crawler_log.json"):
# if json exists -> read in file
with open('out/aktuell_crawler_log.json', 'r') as jsonfile:
self.log = json.load(jsonfile)
else:
# if json doesn't exist -> #1 create json -> #2 write in initial structure -> #3 read it in
# 1
open("out/aktuell_crawler_log.json", "x")
# 2
initial_dict = {"done": []}
with open("out/aktuell_crawler_log.json", "w") as jsonfile:
jsonfile.write(json.dumps(initial_dict))
# 3
with open('out/aktuell_crawler_log.json', 'r') as jsonfile:
self.log = json.load(jsonfile)
for url in urls:
if url["link"] not in self.log["done"]:
yield scrapy.Request(url=url["link"], callback=self.parse)
self.log["done"].append(url["link"])
with open("out/aktuell_crawler_log.json", "w") as jsonfile:
jsonfile.write(json.dumps(self.log))
else:
continue
def parse(self, response):
subtitle = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/h2[contains(@class, "card-subtitle")]/text()').get()
maintitle = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/h2[contains(@class, "card-title")]/text()').get()
tags_num = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/ul/li').getall()
tags = []
for p in range(len(tags_num)):
tag = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/ul/li[' + str(p + 1) + ']/a/text()').get()
if tag != None:
tags.append(tag)
author = ""
date = ""
if response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[1]/text()').get() == "von ":
author = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[1]/b/text()').get()
date = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[2]/text()').get()
else:
date = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[1]/text()').get()
content_num = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p').getall()
main_content = ""
intro_content = ""
further_content = ""
is_further = False
redaktion = ""
for p in range(len(content_num)):
if p == 0:
current_content = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']/strong').get()
check_h2 = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/h2').get()
if current_content is not None and check_h2 is None:
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
current_content = "".join(current_contents)
intro_content = current_content + " "
else:
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
current_content = "".join(current_contents)
main_content = main_content + current_content + " "
elif is_further:
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
current_content = "".join(current_contents)
if current_content.startswith("Redaktion: "):
redaktion = current_content + " "
else:
further_content = further_content + current_content + " "
else:
current_content = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']/strong/text()').get()
if current_content is not None and current_content.startswith("Weitere Informationen"):
is_further = True
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
current_content = "".join(current_contents)
if current_content.startswith("Redaktion: "):
redaktion = current_content + " "
else:
further_content = further_content + current_content + " "
else:
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
current_content = "".join(current_contents)
if current_content.startswith("Redaktion: "):
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
current_content = "".join(current_contents)
redaktion = current_content + " "
else:
main_content = main_content + current_content + " "
full_content = intro_content + " " + main_content
main_content = main_content.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")
intro_content = intro_content.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")
further_content = further_content.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")
links = self.link_extractor.extract_links(response)
filtered_links = []
for link in links:
l = {"url": link.url, "text": link.text.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")}
filtered_links.append(l)
date_year = ""
if not date == "":
date_year = date[-4:]
date_full = ""
if not date == "":
d1 = date[:2]
d2 = date[3:5]
d3 = date[6:]
date_full = d3 + d2 + d1
yield {
"subtitle": subtitle,
"maintitle": maintitle,
"tags": tags,
"author": author,
"date": date,
"date_year": date_year,
"date_full": date_full,
"intro_content": intro_content,
"main_content": main_content,
"further_content": further_content,
"redaktion": redaktion,
"full_content": full_content,
"links": filtered_links,
"url": response.request.url
}
@@ -0,0 +1,11 @@
# Automatically created by: scrapy startproject
#
# For more information about the [deploy] section see:
# https://scrapyd.readthedocs.io/en/latest/deploy.html
[settings]
default = aktuell.settings
[deploy]
#url = http://localhost:6800/
project = aktuell
@@ -0,0 +1,153 @@
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
from random import randint
import time
import sys
from elasticsearch import Elasticsearch
es = Elasticsearch()
index_name = "aktuell-test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
def getLinks(link, driver):
print("--- Getting Links")
driver.get(link)
time.sleep(randint(5, 7))
links = []
dates = []
dates_year = []
dates_num = []
counter = 1
while True:
# increment counter (counter starts one lower than needed, so the increment is at the start instead of at the end)
counter += 1
# check if end is reached
try:
elem = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b").text
if elem == "Zurück zum Gesamtüberblick":
break
except NoSuchElementException as nsee:
break
# get date
elem = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/span[1]/small").text
y = elem[1:5]
m = elem[6:8]
d = elem[9:11]
# get link
link = ""
try:
link = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b/a").get_attribute('href')
except NoSuchElementException as nsee:
continue
links.append(link)
dates.append(d + "." + m + "." + y)
dates_year.append(y)
dates_num.append(y + m + d)
print(f"--- Number of found links: {len(links)}")
return links, dates, dates_year, dates_num
def getData(driver, link, date, date_year, date_num):
print(f"--- --- {link}")
driver.get(link)
time.sleep(randint(5, 7))
subtitle = ""
try:
subtitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h3").text
except NoSuchElementException as nsee:
pass
maintitle = ""
try:
maintitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h2").text
except NoSuchElementException as nsee:
pass
redaktion = ""
try:
redaktion = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[2]").text
except NoSuchElementException as nsee:
pass
author = ""
if redaktion != "":
if redaktion.startswith("Redaktion: ") and redaktion.find(",") != -1:
author = redaktion[11:redaktion.find(",")]
main_content = ""
try:
main_content = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[1]").text
except NoSuchElementException as nsee:
pass
full_content = main_content
dict = {
"subtitle": subtitle,
"maintitle": maintitle,
"author": author,
"date": date,
"main_content": main_content,
"redaktion": redaktion,
"full_content": full_content,
"date_year": date_year,
"date_full": date_num,
"url": link
}
id = (str(date) + "_" + str(author) + "_" + str(maintitle)).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "")
id = id + "_archiv"
upload(dict, id)
def upload(dict, id):
print("--- Uploading")
try:
es.index(index=index_name, id=id, document=dict)
except Exception as e:
print("--- Error while uploading")
print(e)
def check_elastic_online():
if not es.ping():
sys.exit("No connection to Elasticsearch")
# main - entry point
if __name__ == '__main__':
print("Starting")
check_elastic_online()
years = [2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016]
link_1 = "https://www.uni-due.de/aktuell/archiv-"
link_2 = ".php"
options = Options()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
for year in years:
print(f"Crawling year {year}")
link = link_1 + str(year) + link_2
# get year links
links, dates, dates_year, dates_num = getLinks(link, driver)
for i in range(len(links)):
print(f"--- Crawling Data for current year {year} at {i} / {len(links)}")
getData(driver, links[i], dates[i], dates_year[i], dates_num[i])
driver.close()
print("Finished")
@@ -0,0 +1,3 @@
#please check for right versions of the packages in your environment and update them if necessary
spacy
selenium
+49
View File
@@ -0,0 +1,49 @@
import subprocess
import sys
import os
import shutil
import time
def run_command(command, cwd=None):
"""Run a shell command and exit if it fails."""
result = subprocess.run(command,
shell=True,
cwd=cwd,
#capture_output=True, #supresses output from subprocess
text=True)
if result.returncode != 0:
print(f"Command failed: {command}")
print("Error output:\n", result.stderr)
sys.exit(result.returncode)
if __name__ == "__main__":
start_time = time.time()
base_dir = os.path.dirname(os.path.abspath(__file__))
crawler_dir = os.path.join(base_dir, "aktuell")
out_dir = os.path.join(crawler_dir, "out")
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
os.makedirs(out_dir)
output_file_links = os.path.join(out_dir, "links.json")
output_file_meta = os.path.join(out_dir, "meta.json")
print("Running Scrapy link crawler...")
run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"", cwd=crawler_dir)
print("Running Scrapy meta crawler...")
run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"", cwd=crawler_dir)
print("Running upload script")
run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir)
end_time = time.time()
runtime_seconds = end_time - start_time
runtime_hours = runtime_seconds / 3600
print(f"Runtime: {runtime_hours:.2f} hours")
print("Finished crawling and uploading UDE news articles.")
+275
View File
@@ -0,0 +1,275 @@
from elasticsearch import Elasticsearch
import sys
import os
import json
from datetime import datetime
import time
# elasticsearch-connection should be adjusted
# uni-server
es = Elasticsearch()
index_name = "aktuell-test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
# checks if elastic is up and creates the index if not already done
def check_elastic():
if not es.ping():
sys.exit("No connection to Elasticsearch")
if not es.indices.exists(index=index_name):
settings = {
"analysis": {
"analyzer": {
"searchabilityAnalyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"asciifolding"
]
}
}
}
}
mappings = {
"properties": {
"subtitle": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"maintitle": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"author": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"date": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"date_year": {
"type": "long",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"date_full": {
"type": "long",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"intro_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"main_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"further_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"redaktion": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"full_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"tags": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"tags_nested": {
"type": "nested",
"properties": {
"tag": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
},
#"links": {
# "type": "text",
# "analyzer": "searchabilityAnalyzer",
# "search_analyzer": "searchabilityAnalyzer",
# "fields": {
# "keyword": {
# "type": "keyword",
# "ignore_above": 256
# }
# }
#},
"links_nested": {
"type": "nested",
"properties": {
"url": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
},
"text": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
},
}
}
es.indices.create(index=index_name, mappings=mappings, settings=settings)
def upload(path):
with open(path, "r", encoding='utf-8') as json_file:
try:
json_loaded = json.load(json_file)
for news in json_loaded:
time.sleep(10 / 1000)
id = (str(news["date"]) + "_" + str(news["author"]) + "_" + str(news["maintitle"])).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "")
links_nested = []
links = news["links"]
for link in links:
links_nested.append({"url": link["url"], "text": link["text"].replace(" ", "")})
tags_nested = []
tags = news["tags"]
for p in range(len(tags)):
tags_nested.append({"tag": tags[p]})
dict = {
"subtitle": news["subtitle"],
"maintitle": news["maintitle"],
"tags": news["tags"],
"author": news["author"],
"date": news["date"],
"intro_content": news["intro_content"],
"main_content": news["main_content"],
"further_content": news["further_content"],
"redaktion": news["redaktion"],
"full_content": news["full_content"],
"tags_nested": tags_nested,
"date_year": news["date_year"],
"date_full": news["date_full"],
#"links": news["links"],
"links_nested": links_nested,
"url": news["url"]
}
es.index(index=index_name, id=id, document=dict)
except Exception as e:
print("--- Failed to upload news.")
print(e)
# main - entry point
if __name__ == '__main__':
check_elastic()
if len(sys.argv) != 2:
sys.exit("No path given.")
upload(sys.argv[1])
@@ -0,0 +1,27 @@
{
"FKZ": "Förderkennzeichen",
"Thema des geförderten Vorhabens": "Thema",
"Ressort": "Ressort",
"Ressort_fullname": "Ressort_fullname",
"Referat": "Referat",
"Administrierende Stelle": "Projektträger",
"PT_fullname": "Projektträger_fullname",
"Arb.-Einh.": "Arb.-Einh.",
"Laufzeit von": "funding_start",
"Laufzeit bis": "funding_end",
"Laufzeit":"Laufzeit",
"Förderart": "Förderart",
"Förderempfänger /Auftragnehmer": "Zuwendungsempfänger",
"Gemeindekennziffer": "Gemeindekennziffer",
"Förder- / Auftragssumme (Anteil des Bundes) in EUR": "Fördersumme",
"Stadt/Gemeinde": "Stadt/Gemeinde",
"Ort": "Ort",
"Bundesland": "Bundesland",
"Staat": "Staat",
"Leistungsplansystematik": "Leistungsplansystematik",
"Leistungsplansystematik_fullname": "Leistungsplansystematik_fullname",
"Klartext Leistungsplansystematik": "Klartext Leistungsplansystematik",
"Förderprofil": "Förderprofil",
"Projekt": "Verbundprojekt",
"Ausführende Stelle": "Ausführende Stelle"
}
File diff suppressed because it is too large Load Diff
+262
View File
@@ -0,0 +1,262 @@
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.alert import Alert
from random import randint
import time
import pandas as pd
import json
from datetime import datetime
import sys
from elasticsearch import Elasticsearch, helpers
from elasticsearch.helpers import bulk,BulkIndexError
import os
import hashlib
download_path=os.path.abspath(os.getcwd())
es = Elasticsearch()
def crawl_data(link,driver):
driver.get(link)
search_field = driver.find_element(By.ID,"suche_schnellSuche")
if search_field.is_displayed():
# The element is visible, safe to interact
search_field.send_keys("*")
start_search_btn = driver.find_element(By.XPATH,'/html/body/div[1]/div/div/form[1]/div/fieldset/table/tbody/tr[1]/td[2]/input')
start_search_btn.click()
WebDriverWait(driver, 30).until(
EC.element_to_be_clickable((By.XPATH,'//*[@id="unterNavigation"]/ul/li[4]/div/a'))
)
#Click the Export button to trigger data export
export_button = driver.find_element(By.XPATH,'//*[@id="unterNavigation"]/ul/li[4]/div/a')
export_button.click()
# Wait for the prompt to appear
time.sleep(2)
# Switch to the alert and Clicks the "OK" button
Alert(driver).accept()
print("downloading data")
else:
# The element is likely a honeypot, do not interact
print("Honeypot detected, skipping interaction")
def check_elastic_online():
if not es.ping():
sys.exit("No connection to Elasticsearch")
else :
print("Elasticsearch connection established")
def check_elastic_index(df, index_name):
if not es.indices.exists(index=index_name):
print(index_name + " index wasn't found. Creating a new one..")
settings = {
"analysis": {
"analyzer": {
"searchabilityAnalyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"asciifolding"
]
}
}
}
}
mappings = {}
properties = {}
for key in list(df.columns):
if key in ("funding_start", "funding_end", "datum"):
properties[key] = {
"type": "date",
"format": "dd.MM.yyyy"
}
elif key == "Publikationsdatum":
properties[key] = {
"type": "date",
"format": "yyyy"
}
elif key == "unix_timestamp":
properties[key] = {
"type": "long"
}
elif key == "Fördersumme":
properties[key] = {
"type": "float"
}
elif key == "new":
properties[key] = {
"type": "boolean"
}
else:
properties[key] = {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
mappings["properties"] = properties
es.indices.create(index=index_name, mappings=mappings, settings=settings)
es.indices.refresh(index=index_name)
print("The new index '"+index_name+"' has been created")
else:
print(index_name + " already exists. Uploading data...")
def upload_data(df,index_name):
def fill_docs_to_upload(row):
doc_id = hashlib.sha256(str(row['Förderkennzeichen']).encode('utf-8')).hexdigest()
doc = {
"_op_type": "update", # Update existing documents
"_index": index_name,
"_id": doc_id,
"doc": {
"new":False
},
"upsert":{
**row.to_dict(),
"new":True
}
}
docs_to_upload.append(doc)
print("Uploading data...")
try:
check_elastic_index(df, index_name)
except Exception as e:
print("Error while creating index")
print(e)
docs_to_upload = []
df.apply(fill_docs_to_upload,axis=1)
def bulk_docs(docs,data_rate):
response_sum = 0
for i in range(0, len(docs), data_rate):
try:
response = helpers.bulk(es,docs[i:i + data_rate])
response_sum = response_sum + response[0]
except BulkIndexError as e:
print(f"{len(e.errors)} document(s) failed to index.")
for error in e.errors:
print("Error details:", error)
print ("Upload is completed. "+ str(response_sum) +" documents have been uploaded." )
data_rate = 200
bulk_docs(docs_to_upload,data_rate)
def wait_for_file_complete(download_path,file_name):
while True:
file_path = os.path.join(download_path, file_name)
if os.path.exists(file_path) and not any(
fname.endswith(".part") or fname.endswith(".crdownload")
for fname in os.listdir(download_path)
):
print(f"Download complete: {file_name}")
return True
if any(fname.endswith((".part", ".crdownload")) for fname in os.listdir(download_path)):
time.sleep(1)
else:
time.sleep(1)
def format_data(df):
print("Formattind data...")
df.drop(list(df.filter(regex='.1|Unnamed')), axis=1, inplace=True)
def clean_format(text):
if isinstance(text, str):
if text.startswith('="') and text.endswith('"'):
return text[2:-1]
return text
df.columns = [clean_format(col) for col in df.columns]
df = df.applymap(clean_format)
df["FKZ"] = df["FKZ"].str.replace(' /','/')
json_path = os.path.join(os.path.abspath(os.getcwd()), 'extendingColumns.json')
with open(json_path, 'r', encoding='utf-8') as f:
columnsObj = json.load(f)
for column_name, content in columnsObj.items():
alias_map = content['aliases']
df[content['column_alias']] = df[column_name].map(alias_map)
df['Publikationsdatum'] = df['Laufzeit von'].str.split('.').str[2]
df['unix_timestamp'] = int(time.time())
df['datum'] = datetime.now().strftime("%d.%m.%Y")
df['new'] = True
if len(df['Laufzeit von']) and len(df['Laufzeit bis']):
df['Laufzeit'] = "von " + df['Laufzeit von'] + " bis " + df['Laufzeit bis']
config_path = os.path.join(os.path.abspath(os.getcwd()), 'data_config.json')
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
df.rename(columns=config,inplace=True)
df = df.where(pd.notnull(df), "")
df['Fördersumme'] = pd.to_numeric(
df['Fördersumme'].astype(str)
.str.replace('.', '', regex=False)
.str.replace(',', '.', regex=False),
errors='coerce'
)
return df
def setup_chrome_driver(download_path):
options = Options()
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_experimental_option("prefs", {
"download.default_directory": download_path,
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True,
})
chromedriver_path = "/home/inse/miniconda3/envs/airflow/bin/chromedriver"
service = Service(executable_path=chromedriver_path)
driver = webdriver.Chrome(service=service, options=options)
return driver
# main - entry point
if __name__ == '__main__':
print("Starting")
file_path = os.path.join(os.path.abspath(os.getcwd()), 'Suchliste.csv')
if not os.path.exists(file_path):
driver = setup_chrome_driver(download_path)
link_to_crawl= "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=searchreset"
crawl_data(link_to_crawl,driver)
wait_for_file_complete(download_path, "Suchliste.csv")
driver.close()
file = pd.read_csv(file_path,encoding = "latin1",sep=";")
df = pd.DataFrame(file)
df_formatted = format_data(df)
index_name = "projects_bund_test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
check_elastic_online()
upload_data(df_formatted,index_name)
os.remove(file_path)
@@ -49,7 +49,7 @@ import httpx
from dotenv import load_dotenv
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mapping import PROJECT_TOPICS_MAPPING
from service.scripts.projects.topic_mapper.mapping import PROJECT_TOPICS_MAPPING
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)