Files
smartguide/service/scripts/projects/bund/gpc.data.py
T
arzani e87c62f823
LocationBasedServices/smartguide/pipeline/head This commit looks good
offline crawling scripts for news, bund amd postproc for projects, reworked structure
2026-07-14 16:30:01 +02:00

262 lines
9.1 KiB
Python

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)