outdated DFG crawler added
This commit is contained in:
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"title":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/h1",
|
||||
"cookies":"//*[@id='c-s-bn']",
|
||||
"extend_elements":"html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]//ins[@class='jstree-icon']",
|
||||
"person_link":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/div[1]/span[2]/a",
|
||||
"person_name":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/h1",
|
||||
"person_projects":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[4]/div[1]/ul",
|
||||
"person_meta_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/p[",
|
||||
"person_meta_2":"]",
|
||||
"person_metadata":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]"
|
||||
}
|
||||
Vendored
+328
@@ -0,0 +1,328 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException, WebDriverException, TimeoutException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
from elasticsearch import Elasticsearch
|
||||
|
||||
DEFAULT_WAIT_TIMEOUT = 15
|
||||
SHORT_WAIT_TIMEOUT = 10
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Utilities
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def normalize_key(raw_key):
|
||||
return raw_key.lower().replace("-", " ").replace(" ", "_")
|
||||
|
||||
def get_id(url):
|
||||
return url.split("/")[-1]
|
||||
|
||||
def parse_name(raw: str) -> str:
|
||||
name = raw.replace("\n", " ").strip()
|
||||
parts = name.split(", ", 1)
|
||||
return f"{parts[1]} {parts[0]}" if len(parts) == 2 else name
|
||||
|
||||
def does_elem_exist(driver, xpath):
|
||||
try:
|
||||
driver.find_element(By.XPATH, xpath)
|
||||
return True
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
|
||||
def safe_get_text_from_xpath(driver, xpath, timeout=SHORT_WAIT_TIMEOUT):
|
||||
try:
|
||||
element = WebDriverWait(driver, timeout).until(
|
||||
EC.presence_of_element_located((By.XPATH, xpath))
|
||||
)
|
||||
text = element.text.replace("\n", " ").strip()
|
||||
return text if text else ""
|
||||
except (TimeoutException, NoSuchElementException, WebDriverException):
|
||||
return ""
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Log helpers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def load_log(log_name="dfg_data_crawler_log.json"):
|
||||
if os.path.exists(log_name):
|
||||
with open(log_name, 'r') as f:
|
||||
return json.load(f)
|
||||
log = {"done": [], "failed": []}
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
return log
|
||||
|
||||
def save_log(log, log_name="dfg_data_crawler_log.json"):
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Page setup
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def load_page(driver, url, config):
|
||||
"""Navigate to URL and wait for title element. Retries once on timeout."""
|
||||
driver.get(url)
|
||||
try:
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["person_name"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print(f"Timeout on {url}, retrying...")
|
||||
driver.get(url)
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["person_name"]))
|
||||
)
|
||||
|
||||
def accept_cookies(driver, config):
|
||||
try:
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.element_to_be_clickable((By.XPATH, config["cookies"]))
|
||||
).click()
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
def expand_all_elements(driver, config):
|
||||
for e in driver.find_elements(By.XPATH, config["extend_elements"]):
|
||||
try:
|
||||
e.click()
|
||||
except:
|
||||
pass
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Metadata block scraper (shared pattern)
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_metadata_block(driver, data, data_names, path_prefix_1, path_prefix_2, start=1, label_prefix=""):
|
||||
"""
|
||||
Iterates over span-based metadata rows (label in span[1], value in span[2]).
|
||||
Optionally prefixes keys with label_prefix (e.g. 'person_results_').
|
||||
"""
|
||||
counter = start
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
while does_elem_exist(driver, elem_path):
|
||||
try:
|
||||
raw_label = safe_get_text_from_xpath(driver, elem_path + "/span[1]")
|
||||
label = label_prefix + normalize_key(raw_label)
|
||||
|
||||
if label:
|
||||
if label not in data_names:
|
||||
data_names.append(label)
|
||||
data[label] = safe_get_text_from_xpath(driver, elem_path + "/span[2]")
|
||||
|
||||
# collect anchor urls inside span[2]
|
||||
anchors = driver.find_elements(By.XPATH, elem_path + "/span[2]/a")
|
||||
if anchors:
|
||||
ids = [get_id(a.get_attribute('href')) for a in anchors]
|
||||
urls = [a.get_attribute('href') for a in anchors]
|
||||
for key, val in [(label + "_ids", ids), (label + "_urls", urls)]:
|
||||
if key not in data_names:
|
||||
data_names.append(key)
|
||||
data[key] = val
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
counter += 1
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
def scrape_person_details_block(driver, data, data_names, path_prefix_1, path_prefix_2, start=1, label_prefix=""):
|
||||
"""
|
||||
Iterates over span-based metadata rows (label in span[1], value in span[2]).
|
||||
Optionally prefixes keys with label_prefix (e.g. 'person_results_').
|
||||
"""
|
||||
counter = start
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
while does_elem_exist(driver, elem_path):
|
||||
try:
|
||||
raw_label = safe_get_text_from_xpath(driver, elem_path + "/span[1]")
|
||||
label = label_prefix + normalize_key(raw_label)
|
||||
|
||||
if label:
|
||||
if label not in data_names:
|
||||
data_names.append(label)
|
||||
data[label] = safe_get_text_from_xpath(driver, elem_path + "/span[2]")
|
||||
|
||||
# collect anchor urls inside span[2]
|
||||
anchors = driver.find_elements(By.XPATH, elem_path + "/span[2]/a")
|
||||
if anchors:
|
||||
ids = [get_id(a.get_attribute('href')) for a in anchors]
|
||||
urls = [a.get_attribute('href') for a in anchors]
|
||||
for key, val in [(label + "_ids", ids), (label + "_urls", urls)]:
|
||||
if key not in data_names:
|
||||
data_names.append(key)
|
||||
data[key] = val
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
counter += 1
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Section scrapers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_person_details(driver, data, data_names, config):
|
||||
"""Scrape name/metadata, then navigate back."""
|
||||
print("Fetching person details")
|
||||
try:
|
||||
#person details
|
||||
if does_elem_exist(driver,config["person_metadata"]):
|
||||
data["name"] = safe_get_text_from_xpath(driver, config["person_name"])
|
||||
print ("META")
|
||||
scrape_metadata_block(
|
||||
driver, data, data_names,
|
||||
config["person_meta_1"], config["person_meta_2"],
|
||||
start=1
|
||||
)
|
||||
|
||||
for element in driver.find_elements(By.XPATH, config["person_projects"] + "/li"):
|
||||
try:
|
||||
role_text = element.find_element(By.XPATH, "./a").get_attribute("textContent").strip()
|
||||
except NoSuchElementException:
|
||||
role_text = "Unknown Role"
|
||||
try:
|
||||
|
||||
cat_text = element.find_element(By.XPATH, "./ul/li/a").get_attribute("textContent").strip()
|
||||
print(cat_text)
|
||||
except NoSuchElementException:
|
||||
cat_text = None
|
||||
|
||||
walk(li=element, data=data, role=role_text, category=cat_text)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Person metadata error: {e}")
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Walk (recursive person metadata)
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def walk(li, data, role="unknown_role", category=None):
|
||||
try:
|
||||
label = li.find_element(By.XPATH, "./a").get_attribute("textContent").strip()
|
||||
except:
|
||||
label = None
|
||||
|
||||
try:
|
||||
full_text = li.get_attribute("textContent")
|
||||
item_type = full_text.split("(")[-1].replace(")", "").replace("\n","").replace("\t","").strip() if "(" in full_text else None
|
||||
except:
|
||||
item_type = None
|
||||
|
||||
if role is None and label:
|
||||
role = label
|
||||
role = normalize_key(role)
|
||||
|
||||
if role:
|
||||
data.setdefault(role, [])
|
||||
|
||||
if category is None and label:
|
||||
category = label
|
||||
if category:
|
||||
category = normalize_key(category)
|
||||
|
||||
projects = li.find_elements(
|
||||
By.XPATH,
|
||||
"./ul[contains(@class,'projectList')]//a[contains(@class,'person-project-link')]"
|
||||
)
|
||||
for project in projects:
|
||||
data[role].append({
|
||||
"title": project.get_attribute("textContent").strip(),
|
||||
"id": get_id(project.get_attribute("href")),
|
||||
"url": project.get_attribute("href"),
|
||||
"category": category,
|
||||
"type": item_type
|
||||
})
|
||||
|
||||
for child in li.find_elements(By.XPATH, "./ul/li[./a]"):
|
||||
walk(li=child, data=data, role=role)
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Main pipeline
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_person(driver, url, config, data_names):
|
||||
"""Scrape a single person page. Returns data dict or None on failure."""
|
||||
data = {
|
||||
"url": url,
|
||||
"id": url[url.rfind("/") + 1:]
|
||||
}
|
||||
|
||||
# 1. Load page
|
||||
load_page(driver, url, config)
|
||||
|
||||
# 2. Accept cookies (only fires once, then silently skipped)
|
||||
accept_cookies(driver, config)
|
||||
|
||||
# 3. Expand collapsed sections
|
||||
expand_all_elements(driver, config)
|
||||
|
||||
# 4. Scrapte basic infos
|
||||
# 5 Click through to person page and scrape details
|
||||
scrape_person_details(driver=driver, data=data,data_names=data_names, config=config)
|
||||
|
||||
return data
|
||||
|
||||
def person_level(driver, person_links, config):
|
||||
log = load_log()
|
||||
data_names = ["id", "url",]
|
||||
data_list = []
|
||||
|
||||
for i, url in enumerate(person_links[-1:]):
|
||||
print(f"[{i+1}/{len(person_links)}] {url}")
|
||||
|
||||
if url in log["done"]:
|
||||
print(" Already crawled, skipping.")
|
||||
continue
|
||||
|
||||
try:
|
||||
data = scrape_person(driver, url, config, data_names)
|
||||
data_list.append(data)
|
||||
log["done"].append(url)
|
||||
except Exception as e:
|
||||
print(f" Failed: {e}")
|
||||
log["failed"].append(url)
|
||||
|
||||
save_log(log)
|
||||
|
||||
with open("data.json", "w") as f:
|
||||
json.dump(data_list, f)
|
||||
# ─────────────────────────────────────────────
|
||||
# Entry point
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def read_config(path):
|
||||
with open(path, 'r') as f:
|
||||
return json.load(f)
|
||||
|
||||
def readInLinks():
|
||||
with open("links.json", "r", encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
#check_elastic_online()
|
||||
|
||||
person_links = readInLinks()
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
driver = webdriver.Chrome(options=options)
|
||||
|
||||
print(f"Number of persons: {len(person_links)}")
|
||||
config = read_config("data_config.json")
|
||||
person_level(driver, person_links, config)
|
||||
|
||||
driver.close()
|
||||
print("Finished")
|
||||
Vendored
+159
@@ -0,0 +1,159 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.common.exceptions import WebDriverException
|
||||
from selenium.common.exceptions import TimeoutException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from random import randint
|
||||
import time
|
||||
import sys
|
||||
from elasticsearch import Elasticsearch
|
||||
import os
|
||||
import json
|
||||
|
||||
DEFAULT_WAIT_TIMEOUT = 10
|
||||
SHORT_WAIT_TIMEOUT = 5
|
||||
|
||||
def does_elem_exist(driver, xpath):
|
||||
try:
|
||||
driver.find_element(By.XPATH, xpath)
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
return True
|
||||
|
||||
def read_config(path):
|
||||
with open(path, 'r') as jsonfile:
|
||||
config = json.load(jsonfile)
|
||||
return config
|
||||
|
||||
|
||||
def getLinks(driver,config):
|
||||
print("Starting first level.")
|
||||
project_links = []
|
||||
|
||||
log = {}
|
||||
log_name = "dfg_links_crawler_log.json"
|
||||
if os.path.exists(log_name):
|
||||
# if json exists -> read in file
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
else:
|
||||
# if json doesn't exist -> #1 create json -> #2 write in initial structure -> #3 read it in
|
||||
# 1
|
||||
open(log_name, "x")
|
||||
# 2
|
||||
initial_dict = {"done": []}
|
||||
with open(log_name, "w") as jsonfile:
|
||||
jsonfile.write(json.dumps(initial_dict))
|
||||
# 3
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
|
||||
index_counter = 0
|
||||
dfg_link_all_1 = config["start_url_1"]
|
||||
dfg_link_all_2 = config["start_url_2"]
|
||||
|
||||
while True:
|
||||
# #TO REMOVE
|
||||
# if (index_counter >=50):
|
||||
# break
|
||||
print(" - " + str(index_counter))
|
||||
if index_counter in log["done"]:
|
||||
print("- - Already crawled!")
|
||||
index_counter = index_counter + 50000
|
||||
continue
|
||||
|
||||
dfg_link_all = dfg_link_all_1 + str(index_counter) + dfg_link_all_2
|
||||
|
||||
driver.get(dfg_link_all)
|
||||
|
||||
# Wait for the results header to be present
|
||||
try:
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["results_header"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print(f"Timeout waiting for results header on {dfg_link_all}. Continuing to next checks.")
|
||||
|
||||
# cookies
|
||||
try:
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.element_to_be_clickable((By.XPATH, config["cookies"]))
|
||||
).click()
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
# check if side exists, if not -> break loop (all links found)
|
||||
try:
|
||||
no_results_element = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["no_results"]))
|
||||
)
|
||||
text = no_results_element.text
|
||||
if text == "Ihre Suche ergab leider keine Treffer.":
|
||||
break
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
# get project_links
|
||||
# Construct a common XPath for all project links based on the config parts
|
||||
common_links_xpath = config["link_1"] + "*" + config["link_2"]
|
||||
|
||||
try:
|
||||
# Wait for all project links to be present and retrieve them as a list of WebElements
|
||||
elements = WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.XPATH, common_links_xpath))
|
||||
)
|
||||
|
||||
# Extract all href attributes from the retrieved elements at once
|
||||
links = [elem.get_attribute('href') for elem in elements if elem.get_attribute('href')]
|
||||
project_links.extend(links)
|
||||
print(f"Found {len(links)} person links on this page.")
|
||||
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
print("No project links found on this page within the timeout or element not found.")
|
||||
|
||||
log["done"].append(index_counter)
|
||||
index_counter = index_counter + 50
|
||||
|
||||
# write new log
|
||||
with open(log_name, "w") as outfile:
|
||||
outfile.write(json.dumps(log))
|
||||
|
||||
return project_links
|
||||
|
||||
def write_links(project_links):
|
||||
print(len(project_links))
|
||||
js = []
|
||||
if os.path.exists("links.json"):
|
||||
with open("links.json", 'r') as jsonfile:
|
||||
js = json.load(jsonfile)
|
||||
|
||||
for j in js:
|
||||
if j not in project_links:
|
||||
project_links.append(j)
|
||||
|
||||
with open("links.json", "w") as f:
|
||||
json.dump(project_links, f)
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
driver = webdriver.Chrome(options=options)
|
||||
config = read_config("links_config.json")
|
||||
project_links = getLinks(driver,config)
|
||||
|
||||
print("Number of persons: " + str(len(project_links)))
|
||||
|
||||
write_links(project_links)
|
||||
|
||||
driver.close()
|
||||
|
||||
print("Finished")
|
||||
extern/generic-project-crawler/project-crawler-v4-all/DFG_outdated_crawler/persons/links_config.json
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"start_url_1":"https://gepris.dfg.de/gepris/OCTOPUS?beginOfFunding=&bewilligungsStatus=&bundesland=DEU%23&context=person&einrichtungsart=-1&fachgebiet=%23&findButton=historyCall&gefoerdertIn=&ggsHunderter=0&hitsPerPage=50&index=",
|
||||
"start_url_2":"&nurProjekteMitAB=false&oldGgsHunderter=0&oldfachgebiet=%23&orderBy=gz&pemu=%23&task=doKatalog&teilprojekte=true&zk_transferprojekt=false",
|
||||
"results_header":"/html/body/div[1]/div/div[3]/div[1]/div/div/h1",
|
||||
"no_results":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[2]/div/p",
|
||||
"cookies":"//*[@id='c-s-bn']",
|
||||
"link_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[1]/div/div[2]/div[3]/div[",
|
||||
"link_2":"]/div[1]/h2/a"
|
||||
}
|
||||
extern/generic-project-crawler/project-crawler-v4-all/DFG_outdated_crawler/projects/data_config.json
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"title":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/h1",
|
||||
"cookies":"//*[@id='c-s-bn']",
|
||||
"extend_elements":"html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]//ins[@class='jstree-icon']",
|
||||
"description":"//*[@id='projekttext']",
|
||||
"primary_metadata_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/div[",
|
||||
"primary_metadata_2":"]",
|
||||
"metadata_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[3]/div[1]/div[",
|
||||
"metadata_2":"]",
|
||||
"person_link":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/div[1]/span[2]/a",
|
||||
"person_name":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/h1",
|
||||
"person_address":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/p[1]/span[2]",
|
||||
"person_metadata":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[4]/div[1]/ul",
|
||||
"current_projects":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[3]/div[1]/h2",
|
||||
"current_projects_ul":"//div[@id='laufendeProjekte']//ul[contains(@class,'projectList')]",
|
||||
"project_results_button":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/ul/li[2]/a",
|
||||
"project_results_summary":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[3]/div[1]/p",
|
||||
"project_results_header":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[3]/div[1]/h2",
|
||||
"project_results_publications_ul":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[3]/div[1]/ul"
|
||||
|
||||
}
|
||||
Vendored
+422
@@ -0,0 +1,422 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException, WebDriverException, TimeoutException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
|
||||
DEFAULT_WAIT_TIMEOUT = 15
|
||||
SHORT_WAIT_TIMEOUT = 10
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Utilities
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def normalize_key(raw_key):
|
||||
return raw_key.lower().replace("-", " ").replace(" ", "_")
|
||||
|
||||
def get_id(url):
|
||||
return url.split("/")[-1]
|
||||
|
||||
def parse_name(raw: str) -> str:
|
||||
name = raw.replace("\n", " ").strip()
|
||||
parts = name.split(", ", 1)
|
||||
return f"{parts[1]} {parts[0]}" if len(parts) == 2 else name
|
||||
|
||||
def does_elem_exist(driver, xpath):
|
||||
try:
|
||||
driver.find_element(By.XPATH, xpath)
|
||||
return True
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
|
||||
def safe_get_text_from_xpath(driver, xpath, timeout=SHORT_WAIT_TIMEOUT):
|
||||
try:
|
||||
element = WebDriverWait(driver, timeout).until(
|
||||
EC.presence_of_element_located((By.XPATH, xpath))
|
||||
)
|
||||
text = element.text.replace("\n", " ").strip()
|
||||
return text if text else ""
|
||||
except (TimeoutException, NoSuchElementException, WebDriverException):
|
||||
return ""
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Log helpers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def load_log(log_name="dfg_data_crawler_log.json"):
|
||||
if os.path.exists(log_name):
|
||||
with open(log_name, 'r') as f:
|
||||
return json.load(f)
|
||||
log = {"done": [], "failed": []}
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
return log
|
||||
|
||||
def save_log(log, log_name="dfg_data_crawler_log.json"):
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Page setup
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def load_page(driver, url, config):
|
||||
"""Navigate to URL and wait for title element. Retries once on timeout."""
|
||||
driver.get(url)
|
||||
try:
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["title"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print(f"Timeout on {url}, retrying...")
|
||||
driver.get(url)
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["title"]))
|
||||
)
|
||||
|
||||
def accept_cookies(driver, config):
|
||||
try:
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.element_to_be_clickable((By.XPATH, config["cookies"]))
|
||||
).click()
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
def expand_all_elements(driver, config):
|
||||
for e in driver.find_elements(By.XPATH, config["extend_elements"]):
|
||||
try:
|
||||
e.click()
|
||||
except:
|
||||
pass
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Metadata block scraper (shared pattern)
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_metadata_block(driver, data, data_names, path_prefix_1, path_prefix_2, start=1, label_prefix=""):
|
||||
"""
|
||||
Iterates over span-based metadata rows (label in span[1], value in span[2]).
|
||||
Optionally prefixes keys with label_prefix (e.g. 'project_results_').
|
||||
"""
|
||||
counter = start
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
while does_elem_exist(driver, elem_path):
|
||||
try:
|
||||
raw_label = safe_get_text_from_xpath(driver, elem_path + "/span[1]")
|
||||
label = label_prefix + normalize_key(raw_label)
|
||||
|
||||
if label:
|
||||
if label not in data_names:
|
||||
data_names.append(label)
|
||||
data[label] = safe_get_text_from_xpath(driver, elem_path + "/span[2]")
|
||||
|
||||
# collect anchor urls inside span[2]
|
||||
anchors = driver.find_elements(By.XPATH, elem_path + "/span[2]/a")
|
||||
if anchors:
|
||||
ids = [get_id(a.get_attribute('href')) for a in anchors]
|
||||
urls = [a.get_attribute('href') for a in anchors]
|
||||
for key, val in [(label + "_ids", ids), (label + "_urls", urls)]:
|
||||
if key not in data_names:
|
||||
data_names.append(key)
|
||||
data[key] = val
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
counter += 1
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Section scrapers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_basic_info(driver, data, config):
|
||||
data["title"] = safe_get_text_from_xpath(driver, config["title"])
|
||||
data["description"] = safe_get_text_from_xpath(driver, config["description"])
|
||||
|
||||
def scrape_funding_years(data):
|
||||
"""Parse funding_start / funding_end from the 'förderung' field if present."""
|
||||
förderung = data.get("förderung", "")
|
||||
if not förderung:
|
||||
return
|
||||
if "seit" in förderung:
|
||||
data["funding_start"] = int(förderung[-4:])
|
||||
data["funding_end"] = 2999
|
||||
elif "in" in förderung:
|
||||
data["funding_start"] = int(förderung[-4:])
|
||||
data["funding_end"] = int(förderung[-4:])
|
||||
elif "von" in förderung:
|
||||
data["funding_start"] = int(förderung[-13:-9])
|
||||
data["funding_end"] = int(förderung[-4:])
|
||||
|
||||
def scrape_project_results(driver, data, data_names, config):
|
||||
if not does_elem_exist(driver, config["project_results_button"]):
|
||||
return
|
||||
print("Fetching project results")
|
||||
try:
|
||||
driver.find_element(By.XPATH, config["project_results_button"]).click()
|
||||
scrape_metadata_block(
|
||||
driver, data, data_names,
|
||||
config["metadata_1"], config["metadata_2"],
|
||||
start=1,
|
||||
label_prefix="project_results_"
|
||||
)
|
||||
if does_elem_exist(driver, config["project_results_summary"]):
|
||||
data["project_results_summary"] = safe_get_text_from_xpath(
|
||||
driver, config["project_results_summary"]
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"project results error: {e}")
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Running projects & publications
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def handle_current_projects(driver, xpath, data):
|
||||
print("Handling running projects")
|
||||
try:
|
||||
items = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.XPATH, xpath + "/li"))
|
||||
)
|
||||
except TimeoutException:
|
||||
print("Running projects not found")
|
||||
return data
|
||||
|
||||
data["current_projects"] = []
|
||||
for li in items:
|
||||
try:
|
||||
title_el = li.find_element(By.XPATH, "./a[1]")
|
||||
project = {
|
||||
"project_title": title_el.get_attribute("textContent").replace("\n", " ").strip(),
|
||||
"project_url": title_el.get_attribute("href"),
|
||||
"project_id": get_id(title_el.get_attribute("href")),
|
||||
"teilprojektleiter": [
|
||||
{
|
||||
"name": parse_name(p.get_attribute("textContent")),
|
||||
"id": get_id(p.get_attribute("href")),
|
||||
"url": p.get_attribute("href")
|
||||
}
|
||||
for p in li.find_elements(By.XPATH, ".//a[contains(@href,'/gepris/person/')]")
|
||||
],
|
||||
"meta_raw": li.get_attribute("textContent").replace("\n", " ").strip()
|
||||
}
|
||||
data["current_projects"].append(project)
|
||||
except Exception as e:
|
||||
print(f"Running project parse error: {e}")
|
||||
return data
|
||||
|
||||
def handle_running_projects(driver,xpath,data):
|
||||
print("Handling running projects")
|
||||
items = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.CSS_SELECTOR, xpath+"/li"))
|
||||
)
|
||||
print(len(items))
|
||||
if len(items) > 0:
|
||||
try:
|
||||
data["running_projects"] = []
|
||||
for li in items:
|
||||
project={}
|
||||
title_el = li.find_element(By.XPATH, "./a[1]")
|
||||
project["project_title"] = title_el.text.replace("\n", " ").strip()
|
||||
project["project_url"] = title_el.get_attribute("href")
|
||||
project["project_id"] = get_id(title_el.get_attribute("href"))
|
||||
project["teilprojektleiter"] = [
|
||||
{
|
||||
"name": parse_name(p.text),
|
||||
"id": get_id(p.get_attribute("href")),
|
||||
"url": p.get_attribute("href")
|
||||
}
|
||||
for p in li.find_elements(By.XPATH, ".//a[contains(@href,'/gepris/person/')]")
|
||||
]
|
||||
full_text = li.get_attribute("textContent")
|
||||
project["meta_raw"] = full_text
|
||||
data["running_projects"].append(project)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return data
|
||||
|
||||
def handle_project_results_publications(driver, xpath, data):
|
||||
print("Handling publications")
|
||||
try:
|
||||
items = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.XPATH, xpath + "/li"))
|
||||
)
|
||||
except TimeoutException:
|
||||
print("Publications not found")
|
||||
return data
|
||||
|
||||
data["project_results_publications"] = []
|
||||
for li in items:
|
||||
try:
|
||||
headline = li.find_element(By.XPATH, ".//span[contains(@class,'publications-headline')]")
|
||||
title = headline.text.replace("\n", " ").strip()
|
||||
try:
|
||||
url = headline.find_element(By.XPATH, ".//a").get_attribute("href")
|
||||
except NoSuchElementException:
|
||||
url = None
|
||||
|
||||
full_text = li.get_attribute("textContent").strip()
|
||||
data["project_results_publications"].append({
|
||||
"title": title,
|
||||
"url": url,
|
||||
"authors_raw": full_text.replace(title, "", 1).strip(),
|
||||
"meta_raw": full_text
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"Publication parse error: {e}")
|
||||
return data
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Main pipeline
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_project(driver, url, config, data_names):
|
||||
"""Scrape a single project page. Returns data dict or None on failure."""
|
||||
data = {
|
||||
"url": url,
|
||||
"id": url[url.rfind("/") + 1:]
|
||||
}
|
||||
|
||||
# 1. Load page
|
||||
load_page(driver, url, config)
|
||||
|
||||
# 2. Accept cookies (only fires once, then silently skipped)
|
||||
accept_cookies(driver, config)
|
||||
|
||||
# 3. Expand collapsed sections
|
||||
expand_all_elements(driver, config)
|
||||
|
||||
# 4. Title + description
|
||||
scrape_basic_info(driver, data, config)
|
||||
|
||||
# 5. Primary metadata block (upper details)
|
||||
print("Fetching primary metadata")
|
||||
scrape_metadata_block(
|
||||
driver, data, data_names,
|
||||
config["primary_metadata_1"], config["primary_metadata_2"],
|
||||
start=1
|
||||
)
|
||||
|
||||
# 6. Running sub-projects (if present)
|
||||
if does_elem_exist(driver, config["current_projects"]):
|
||||
data = handle_current_projects(driver, config["current_projects_ul"], data)
|
||||
|
||||
# 7. Secondary metadata block (lower details)
|
||||
print("Fetching secondary metadata")
|
||||
scrape_metadata_block(
|
||||
driver, data, data_names,
|
||||
config["metadata_1"], config["metadata_2"],
|
||||
start=2
|
||||
)
|
||||
|
||||
# 8. Project results section (click button → scrape)
|
||||
scrape_project_results(driver, data, data_names, config)
|
||||
|
||||
# 9. Publications list
|
||||
if does_elem_exist(driver, config["project_results_publications_ul"]):
|
||||
data = handle_project_results_publications(
|
||||
driver, config["project_results_publications_ul"], data
|
||||
)
|
||||
|
||||
# 10. Derive funding years from 'förderung' field
|
||||
scrape_funding_years(data)
|
||||
|
||||
# 11. Click through to person page and scrape details
|
||||
#scrape_person_details(driver=driver, data=data,data_names=data_names, config=config)
|
||||
|
||||
return data
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
def project_level(driver, project_links, config):
|
||||
log = load_log()
|
||||
|
||||
data_names = [
|
||||
"id", "url", "title", "description", "funding_start", "funding_end",
|
||||
"person_creator_url", "person_creator_id", "person_creator_name",
|
||||
"person_creator_address"
|
||||
]
|
||||
|
||||
# Load existing data if present
|
||||
if os.path.exists("data.json"):
|
||||
with open("data.json", "r", encoding="utf-8") as f:
|
||||
data_list = json.load(f)
|
||||
else:
|
||||
data_list = []
|
||||
|
||||
new_entries = 0
|
||||
|
||||
for i, url in enumerate(project_links):
|
||||
print(f"[{i+1}/{len(project_links)}] {url}")
|
||||
|
||||
if url in log["done"]:
|
||||
print(" Already crawled, skipping.")
|
||||
continue
|
||||
|
||||
try:
|
||||
data = scrape_project(driver, url, config, data_names)
|
||||
|
||||
data_list.append(data)
|
||||
log["done"].append(url)
|
||||
new_entries += 1
|
||||
|
||||
# Save every 10 successful entries
|
||||
if new_entries % 10 == 0:
|
||||
with open("data.json", "w", encoding="utf-8") as f:
|
||||
json.dump(data_list, f, ensure_ascii=False, indent=2)
|
||||
|
||||
save_log(log)
|
||||
print(f" Saved progress ({new_entries} new entries).")
|
||||
|
||||
except Exception as e:
|
||||
print(f" Failed: {e}")
|
||||
log["failed"].append(url)
|
||||
save_log(log)
|
||||
|
||||
# Final save
|
||||
with open("data.json", "w", encoding="utf-8") as f:
|
||||
json.dump(data_list, f, ensure_ascii=False, indent=2)
|
||||
|
||||
save_log(log)
|
||||
|
||||
print(f"Finished. Total records: {len(data_list)}")
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Entry point
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def read_config(path):
|
||||
with open(path, 'r') as f:
|
||||
return json.load(f)
|
||||
|
||||
def readInLinks():
|
||||
with open("links.json", "r", encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
#check_elastic_online()
|
||||
|
||||
project_links = readInLinks()
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
driver = webdriver.Chrome(options=options)
|
||||
|
||||
print(f"Number of projects: {len(project_links)}")
|
||||
config = read_config("data_config.json")
|
||||
project_level(driver, project_links, config)
|
||||
|
||||
driver.close()
|
||||
print("Finished")
|
||||
extern/generic-project-crawler/project-crawler-v4-all/DFG_outdated_crawler/projects/dfg_data_copy.py
Vendored
+575
@@ -0,0 +1,575 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.common.exceptions import WebDriverException
|
||||
from selenium.common.exceptions import TimeoutException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
import traceback
|
||||
from random import randint
|
||||
import time
|
||||
import sys
|
||||
from elasticsearch import Elasticsearch
|
||||
import os
|
||||
import json
|
||||
|
||||
DEFAULT_WAIT_TIMEOUT = 15
|
||||
SHORT_WAIT_TIMEOUT = 10
|
||||
|
||||
es = Elasticsearch({'host':'inse.nes.uni-due.de', 'port': 443, 'path_prefix':'elastic', 'scheme':'https'}, basic_auth=('elastic', 'RLldUaJgbGeoqd3KCX3p'), request_timeout=60, max_retries=5, retry_on_timeout=True)
|
||||
|
||||
def does_elem_exist(driver, xpath):
|
||||
try:
|
||||
driver.find_element(By.XPATH, xpath)
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
return True
|
||||
|
||||
def safe_get_text_from_xpath(driver, xpath, timeout=SHORT_WAIT_TIMEOUT):
|
||||
"""Safe function to retrieve text from an element"""
|
||||
try:
|
||||
element = WebDriverWait(driver, timeout).until(
|
||||
EC.presence_of_element_located((By.XPATH, xpath))
|
||||
)
|
||||
# Selenium's .text attribute returns the visible text.
|
||||
text = element.text.replace("\n", " ").strip()
|
||||
return text if text else ""
|
||||
except (TimeoutException, NoSuchElementException, WebDriverException):
|
||||
return ""
|
||||
|
||||
# def safe_get_text_from_el( el, timeout=SHORT_WAIT_TIMEOUT):
|
||||
# """Safe function to retrieve text from an element"""
|
||||
# try:
|
||||
# text = el.text.replace("\n", " ").strip()
|
||||
# print(text)
|
||||
# return text if text else ""
|
||||
# except (TimeoutException, NoSuchElementException, WebDriverException):
|
||||
# return ""
|
||||
|
||||
def project_level(driver, project_links,config):
|
||||
print("Starting project level.")
|
||||
|
||||
# start log
|
||||
log = {}
|
||||
log_name = "dfg_data_crawler_log.json"
|
||||
if os.path.exists(log_name):
|
||||
# if json exists -> read in file
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
else:
|
||||
# if json doesn't exist -> #1 create json -> #2 write in initial structure -> #3 read it in
|
||||
# 1
|
||||
open(log_name, "x")
|
||||
# 2
|
||||
initial_dict = {"done": [], "failed": []}
|
||||
with open(log_name, "w") as jsonfile:
|
||||
jsonfile.write(json.dumps(initial_dict))
|
||||
# 3
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
|
||||
data_list = []
|
||||
data_names = ["id", "link", "title", "description", "funding_start", "funding_end","person_creator_url", "person_creator_id", "person_creator_name", "person_creator_address"]
|
||||
|
||||
hit_counter = 0
|
||||
for hit in project_links:
|
||||
try:
|
||||
print(hit_counter)
|
||||
hit_counter += 1
|
||||
|
||||
if hit in log["done"]:
|
||||
print("- - Already crawled!")
|
||||
continue
|
||||
|
||||
driver.get(hit)
|
||||
|
||||
# Wait for project page to load instead of fixed sleeps and custom loops
|
||||
try:
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["title"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print(f"Timeout waiting for project title on {hit}. Retrying...")
|
||||
driver.get(hit)
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["title"]))
|
||||
)
|
||||
|
||||
# cookies
|
||||
try:
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.element_to_be_clickable((By.XPATH, config["cookies"]))
|
||||
).click()
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
# extend all elements
|
||||
elems = driver.find_elements(By.XPATH, config["extend_elements"])
|
||||
for e in elems:
|
||||
try:
|
||||
e.click()
|
||||
except:
|
||||
log["failed"].append(hit)
|
||||
continue
|
||||
|
||||
# get infos
|
||||
data = {}
|
||||
data["link"] = hit
|
||||
data["id"] = hit[hit.rfind("/") + 1:]
|
||||
|
||||
data["title"] = safe_get_text_from_xpath(driver, config['title'])
|
||||
data["description"] = safe_get_text_from_xpath(driver, config["description"])
|
||||
print("Fetching primary metadata")
|
||||
# upper details
|
||||
elem_counter = 1
|
||||
elem_path = config["primary_metadata_1"] + str(elem_counter) + config["primary_metadata_2"]
|
||||
while does_elem_exist(driver, elem_path):
|
||||
try:
|
||||
label = normalize_key(safe_get_text_from_xpath(driver, elem_path + "/span[1]"))
|
||||
if len(label)> 0:
|
||||
if label not in data_names:
|
||||
data_names.append(label)
|
||||
|
||||
data[label] = safe_get_text_from_xpath(driver, elem_path + "/span[2]")
|
||||
|
||||
#if url exists
|
||||
try:
|
||||
anchors = driver.find_elements(By.XPATH, elem_path + "/span[2]/a")
|
||||
|
||||
if anchors:
|
||||
ids = [get_id(a.get_attribute('href')) for a in anchors]
|
||||
urls = [a.get_attribute('href') for a in anchors]
|
||||
|
||||
for key, val in [(label + "_ids", ids), (label + "_urls", urls)]:
|
||||
if key not in data_names:
|
||||
data_names.append(key)
|
||||
data[key] = val
|
||||
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
|
||||
elem_counter += 1
|
||||
elem_path = config["primary_metadata_1"] + str(elem_counter) + config["primary_metadata_2"]
|
||||
except:
|
||||
elem_counter += 1
|
||||
elem_path = config["primary_metadata_1"] + str(elem_counter) + config["primary_metadata_2"]
|
||||
|
||||
# lower details
|
||||
# Running projects
|
||||
|
||||
if does_elem_exist(driver, config["running_projects"]):
|
||||
try:
|
||||
data = handle_running_projects(driver=driver,xpath=config["running_projects_ul"],data=data)
|
||||
except:
|
||||
break
|
||||
print("Fetching metadata")
|
||||
elem_counter = 2
|
||||
elem_path = config["metadata_1"] + str(elem_counter) + config["metadata_2"]
|
||||
while does_elem_exist(driver, elem_path):
|
||||
try:
|
||||
label = normalize_key(safe_get_text_from_xpath(driver, elem_path + "/span[1]"))
|
||||
if len(label)> 0:
|
||||
if label not in data_names:
|
||||
data_names.append(label)
|
||||
|
||||
data[label] = safe_get_text_from_xpath(driver, elem_path + "/span[2]")
|
||||
|
||||
#if url exists
|
||||
try:
|
||||
anchors = driver.find_elements(By.XPATH, elem_path + "/span[2]/a")
|
||||
|
||||
if anchors:
|
||||
ids = [get_id(a.get_attribute('href')) for a in anchors]
|
||||
urls = [a.get_attribute('href') for a in anchors]
|
||||
|
||||
for key, val in [(label + "_ids", ids), (label + "_urls", urls)]:
|
||||
if key not in data_names:
|
||||
data_names.append(key)
|
||||
data[key] = val
|
||||
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
|
||||
elem_counter += 1
|
||||
elem_path = config["metadata_1"] + str(elem_counter) + config["metadata_2"]
|
||||
except:
|
||||
elem_counter += 1
|
||||
elem_path = config["metadata_1"] + str(elem_counter) + config["metadata_2"]
|
||||
|
||||
|
||||
#project results
|
||||
if does_elem_exist(driver, config["project_results_button"]):
|
||||
print ("Fetching project results")
|
||||
project_results = driver.find_element(By.XPATH, config["project_results_button"])
|
||||
try:
|
||||
prefix = "project_results_"
|
||||
elem_counter = 1
|
||||
project_results.click()
|
||||
elem_path = config["metadata_1"] + str(elem_counter) + config["metadata_2"]
|
||||
while does_elem_exist(driver, elem_path):
|
||||
try:
|
||||
label = prefix + normalize_key(safe_get_text_from_xpath(driver, elem_path + "/span[1]"))
|
||||
if len(label)> 0:
|
||||
if label not in data_names:
|
||||
data_names.append(label)
|
||||
|
||||
data[label] = safe_get_text_from_xpath(driver, elem_path + "/span[2]")
|
||||
|
||||
#if url exists
|
||||
try:
|
||||
anchors = driver.find_elements(By.XPATH, elem_path + "/span[2]/a")
|
||||
|
||||
if anchors:
|
||||
ids = [get_id(a.get_attribute('href')) for a in anchors]
|
||||
urls = [a.get_attribute('href') for a in anchors]
|
||||
|
||||
for key, val in [(label + "_ids", ids), (label + "_urls", urls)]:
|
||||
if key not in data_names:
|
||||
data_names.append(key)
|
||||
data[key] = val
|
||||
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
|
||||
elem_counter += 1
|
||||
elem_path = config["metadata_1"] + str(elem_counter) + config["metadata_2"]
|
||||
except:
|
||||
elem_counter += 1
|
||||
elem_path = config["metadata_1"] + str(elem_counter) + config["metadata_2"]
|
||||
|
||||
if does_elem_exist(driver, config["project_results_summary"]):
|
||||
data[prefix + "summary"] = safe_get_text_from_xpath(driver, config["project_results_summary"])
|
||||
|
||||
except:
|
||||
pass
|
||||
|
||||
if does_elem_exist(driver, config["project_results_publications_ul"]):
|
||||
try:
|
||||
data = handle_project_results_publications(driver=driver,xpath=config["project_results_publications_ul"],data=data)
|
||||
except:
|
||||
break
|
||||
# get funding_start and funding_end year if possible
|
||||
keysList = list(data.keys())
|
||||
if "förderung" in keysList:
|
||||
if "seit" in data["förderung"]:
|
||||
data["funding_start"] = int(data["förderung"][-4:])
|
||||
data["funding_end"] = 2999
|
||||
elif "in" in data["förderung"]:
|
||||
data["funding_start"] = int(data["förderung"][-4:])
|
||||
data["funding_end"] = int(data["förderung"][-4:])
|
||||
elif "von" in data["förderung"]:
|
||||
data["funding_start"] = int(data["förderung"][-13:-9])
|
||||
data["funding_end"] = int(data["förderung"][-4:])
|
||||
|
||||
print("fetching metadata")
|
||||
# get linked person details
|
||||
try:
|
||||
# 1. find anchor (raises TimeoutException if missing)
|
||||
try:
|
||||
person_anchor = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["person_link"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print("person anchor not found, skipping")
|
||||
person_anchor = None
|
||||
|
||||
if person_anchor:
|
||||
data["person_creator_id"] = get_id(person_anchor.get_attribute('href'))
|
||||
data["person_creator_url"] = person_anchor.get_attribute('href')
|
||||
|
||||
# 2. click and wait for navigation
|
||||
person_anchor.click()
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["person_name"]))
|
||||
)
|
||||
|
||||
data["person_creator_name"] = safe_get_text_from_xpath(driver, config["person_name"])
|
||||
data["person_creator_address"] = safe_get_text_from_xpath(driver, config["person_address"])
|
||||
|
||||
# 3. get persons metadata
|
||||
for element in driver.find_elements(By.XPATH, config["person_metadata"] + "/li"):
|
||||
try:
|
||||
role_text = element.find_element(By.XPATH, "./a").text.strip()
|
||||
except NoSuchElementException:
|
||||
role_text = "Unknown Role"
|
||||
|
||||
try:
|
||||
cat_text = element.find_element(By.XPATH, "./ul/li/a").text.strip()
|
||||
except NoSuchElementException:
|
||||
cat_text = None
|
||||
|
||||
walk(li=element, data=data, role=role_text, category=cat_text)
|
||||
|
||||
except Exception as e:
|
||||
print(f"person metadata error: {e}")
|
||||
|
||||
data_list.append(data)
|
||||
log["done"].append(hit)
|
||||
|
||||
except:
|
||||
log["failed"].append(hit)
|
||||
continue
|
||||
|
||||
# write new log
|
||||
with open(log_name, "w") as outfile:
|
||||
outfile.write(json.dumps(log))
|
||||
|
||||
with open("data.json", "w") as f:
|
||||
json.dump(data_list, f)
|
||||
# # upload infos
|
||||
# print("Uploading")
|
||||
# index_name = "projects_dfg_all"
|
||||
# check_elastic_index(data_names, index_name)
|
||||
|
||||
# for data_hit in data_list:
|
||||
# try:
|
||||
# es.index(index=index_name, id=data_hit["id"], document=data_hit)
|
||||
# except Exception as e:
|
||||
# print("Error while uploading!")
|
||||
# print(e)
|
||||
# continue
|
||||
|
||||
def check_elastic_index(data_names, index_name):
|
||||
if not es.indices.exists(index=index_name):
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"searchabilityAnalyzer": {
|
||||
"type": "custom",
|
||||
"tokenizer": "standard",
|
||||
"filter": [
|
||||
"lowercase",
|
||||
"asciifolding"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mappings = {}
|
||||
properties = {}
|
||||
|
||||
for name in data_names:
|
||||
if name in ("funding_start", "funding_end"):
|
||||
properties[name] = {
|
||||
"type": "integer"
|
||||
}
|
||||
else:
|
||||
properties[name] = {
|
||||
"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)
|
||||
|
||||
def check_elastic_online():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
|
||||
def readInLinks():
|
||||
json_links = {}
|
||||
with open("links.json", "r", encoding='utf-8') as json_links_file:
|
||||
json_links = json.load(json_links_file)
|
||||
return json_links[:1]
|
||||
|
||||
def normalize_key(raw_key):
|
||||
return raw_key.lower().replace("-"," ").replace(" ", "_")
|
||||
|
||||
def get_id(url):
|
||||
return url.split("/")[-1]
|
||||
|
||||
def walk(li, data, role="unknown_role", category=None):
|
||||
try:
|
||||
label = li.find_element(By.XPATH, "./a").text.strip()
|
||||
except:
|
||||
label = None
|
||||
|
||||
try:
|
||||
full_text = li.get_attribute("textContent")
|
||||
parts = full_text.split(")")
|
||||
type = parts[0].split("(")[-1] if "(" in full_text else None
|
||||
except:
|
||||
type = None
|
||||
|
||||
|
||||
if role is None and label:
|
||||
role = label
|
||||
|
||||
role = normalize_key(role)
|
||||
|
||||
if role:
|
||||
data.setdefault(role, [])
|
||||
|
||||
elif category is None and label:
|
||||
category = label
|
||||
|
||||
category = normalize_key(category)
|
||||
|
||||
projects = li.find_elements(
|
||||
By.XPATH,
|
||||
"./ul[contains(@class,'projectList')]//a[contains(@class,'person-project-link')]"
|
||||
)
|
||||
|
||||
for project in projects:
|
||||
title = project.text.strip()
|
||||
|
||||
data[role].append({
|
||||
"title": title,
|
||||
"id": get_id(project.get_attribute("href")),
|
||||
"url": project.get_attribute("href"),
|
||||
"category": category,
|
||||
"type":type.replace(")", "").replace("(", "")
|
||||
})
|
||||
|
||||
for child in li.find_elements(By.XPATH, "./ul/li[./a]"):
|
||||
walk(li=child, data=data, role=role, category=category)
|
||||
|
||||
def handle_running_projects(driver,xpath,data):
|
||||
print("Handling running projects")
|
||||
items = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.XPATH, xpath+"/li"))
|
||||
)
|
||||
print(len(items))
|
||||
if len(items) > 0:
|
||||
try:
|
||||
data["running_projects"] = []
|
||||
for li in items:
|
||||
project={}
|
||||
title_el = li.find_element(By.XPATH, "./a[1]")
|
||||
project["project_title"] = title_el.text.replace("\n", " ").strip()
|
||||
project["project_url"] = title_el.get_attribute("href")
|
||||
project["project_id"] = get_id(title_el.get_attribute("href"))
|
||||
project["teilprojektleiter"] = [
|
||||
{
|
||||
"name": parse_name(p.text),
|
||||
"id": get_id(p.get_attribute("href")),
|
||||
"url": p.get_attribute("href")
|
||||
}
|
||||
for p in li.find_elements(By.XPATH, ".//a[contains(@href,'/gepris/person/')]")
|
||||
]
|
||||
full_text = li.get_attribute("textContent")
|
||||
project["meta_raw"] = full_text
|
||||
data["running_projects"].append(project)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return data
|
||||
|
||||
def handle_running_projects(driver,xpath,data):
|
||||
print("Handling running projects")
|
||||
items = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.CSS_SELECTOR, xpath+"/li"))
|
||||
)
|
||||
print(len(items))
|
||||
if len(items) > 0:
|
||||
try:
|
||||
data["running_projects"] = []
|
||||
for li in items:
|
||||
project={}
|
||||
title_el = li.find_element(By.XPATH, "./a[1]")
|
||||
project["project_title"] = title_el.text.replace("\n", " ").strip()
|
||||
project["project_url"] = title_el.get_attribute("href")
|
||||
project["project_id"] = get_id(title_el.get_attribute("href"))
|
||||
project["teilprojektleiter"] = [
|
||||
{
|
||||
"name": parse_name(p.text),
|
||||
"id": get_id(p.get_attribute("href")),
|
||||
"url": p.get_attribute("href")
|
||||
}
|
||||
for p in li.find_elements(By.XPATH, ".//a[contains(@href,'/gepris/person/')]")
|
||||
]
|
||||
full_text = li.get_attribute("textContent")
|
||||
project["meta_raw"] = full_text
|
||||
data["running_projects"].append(project)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return data
|
||||
def handle_project_results_publications(driver, xpath, data):
|
||||
print("Handling publications")
|
||||
|
||||
items = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.XPATH, xpath + "/li"))
|
||||
)
|
||||
|
||||
print(len(items))
|
||||
|
||||
if len(items) > 0:
|
||||
data["project_results_publications"] = []
|
||||
|
||||
for li in items:
|
||||
publication = {}
|
||||
|
||||
try:
|
||||
headline = li.find_element(
|
||||
By.XPATH,
|
||||
".//span[contains(@class,'publications-headline')]"
|
||||
)
|
||||
|
||||
publication["title"] = headline.text.replace("\n", " ").strip()
|
||||
|
||||
#DOI / external URL
|
||||
try:
|
||||
link = headline.find_element(By.XPATH, ".//a")
|
||||
publication["url"] = link.get_attribute("href")
|
||||
except NoSuchElementException:
|
||||
publication["url"] = None
|
||||
|
||||
# Full text for parsing
|
||||
full_text = li.get_attribute("textContent").strip()
|
||||
|
||||
# Remove title from beginning to get authors
|
||||
authors = full_text.replace(
|
||||
publication["title"],
|
||||
"",
|
||||
1
|
||||
).strip()
|
||||
|
||||
publication["authors_raw"] = authors
|
||||
publication["meta_raw"] = full_text
|
||||
|
||||
data["project_results_publications"].append(publication)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Publication parse error: {e}")
|
||||
|
||||
return data
|
||||
def parse_name(raw: str) -> str:
|
||||
name = raw.replace("\n", " ").strip()
|
||||
parts = name.split(", ", 1)
|
||||
return f"{parts[1]} {parts[0]}" if len(parts) == 2 else name
|
||||
|
||||
def read_config(path):
|
||||
with open(path, 'r') as jsonfile:
|
||||
config = json.load(jsonfile)
|
||||
return config
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
|
||||
check_elastic_online()
|
||||
|
||||
project_links = readInLinks()
|
||||
|
||||
options = Options()
|
||||
#options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
driver = webdriver.Chrome(options=options)
|
||||
|
||||
print("Number of projects: " + str(len(project_links)))
|
||||
config = read_config("data_config.json")
|
||||
project_level(driver, project_links,config)
|
||||
|
||||
driver.close()
|
||||
|
||||
print("Finished")
|
||||
Vendored
+159
@@ -0,0 +1,159 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.common.exceptions import WebDriverException
|
||||
from selenium.common.exceptions import TimeoutException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from random import randint
|
||||
import time
|
||||
import sys
|
||||
from elasticsearch import Elasticsearch
|
||||
import os
|
||||
import json
|
||||
|
||||
DEFAULT_WAIT_TIMEOUT = 10
|
||||
SHORT_WAIT_TIMEOUT = 5
|
||||
|
||||
def does_elem_exist(driver, xpath):
|
||||
try:
|
||||
driver.find_element(By.XPATH, xpath)
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
return True
|
||||
|
||||
def read_config(path):
|
||||
with open(path, 'r') as jsonfile:
|
||||
config = json.load(jsonfile)
|
||||
return config
|
||||
|
||||
|
||||
def getLinks(driver,config):
|
||||
print("Starting first level.")
|
||||
project_links = []
|
||||
|
||||
log = {}
|
||||
log_name = "dfg_links_crawler_log.json"
|
||||
if os.path.exists(log_name):
|
||||
# if json exists -> read in file
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
else:
|
||||
# if json doesn't exist -> #1 create json -> #2 write in initial structure -> #3 read it in
|
||||
# 1
|
||||
open(log_name, "x")
|
||||
# 2
|
||||
initial_dict = {"done": []}
|
||||
with open(log_name, "w") as jsonfile:
|
||||
jsonfile.write(json.dumps(initial_dict))
|
||||
# 3
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
|
||||
index_counter = 0
|
||||
dfg_link_all_1 = config["start_url_1"]
|
||||
dfg_link_all_2 = config["start_url_2"]
|
||||
|
||||
while True:
|
||||
# #TO REMOVE
|
||||
# if (index_counter >=150000):
|
||||
# break
|
||||
print(" - " + str(index_counter))
|
||||
if index_counter in log["done"]:
|
||||
print("- - Already crawled!")
|
||||
index_counter = index_counter + 50
|
||||
continue
|
||||
|
||||
dfg_link_all = dfg_link_all_1 + str(index_counter) + dfg_link_all_2
|
||||
|
||||
driver.get(dfg_link_all)
|
||||
|
||||
# Wait for the results header to be present
|
||||
try:
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["results_header"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print(f"Timeout waiting for results header on {dfg_link_all}. Continuing to next checks.")
|
||||
|
||||
# cookies
|
||||
try:
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.element_to_be_clickable((By.XPATH, config["cookies"]))
|
||||
).click()
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
# check if side exists, if not -> break loop (all links found)
|
||||
try:
|
||||
no_results_element = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["no_results"]))
|
||||
)
|
||||
text = no_results_element.text
|
||||
if text == "Ihre Suche ergab leider keine Treffer.":
|
||||
break
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
# get project_links
|
||||
# Construct a common XPath for all project links based on the config parts
|
||||
common_links_xpath = config["link_1"] + "*" + config["link_2"]
|
||||
|
||||
try:
|
||||
# Wait for all project links to be present and retrieve them as a list of WebElements
|
||||
elements = WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.XPATH, common_links_xpath))
|
||||
)
|
||||
|
||||
# Extract all href attributes from the retrieved elements at once
|
||||
links = [elem.get_attribute('href') for elem in elements if elem.get_attribute('href')]
|
||||
project_links.extend(links)
|
||||
print(f"Found {len(links)} project links on this page.")
|
||||
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
print("No project links found on this page within the timeout or element not found.")
|
||||
|
||||
log["done"].append(index_counter)
|
||||
index_counter = index_counter + 50000
|
||||
|
||||
# write new log
|
||||
with open(log_name, "w") as outfile:
|
||||
outfile.write(json.dumps(log))
|
||||
|
||||
return project_links
|
||||
|
||||
def write_links(project_links):
|
||||
print(len(project_links))
|
||||
js = []
|
||||
if os.path.exists("links.json"):
|
||||
with open("links.json", 'r') as jsonfile:
|
||||
js = json.load(jsonfile)
|
||||
|
||||
for j in js:
|
||||
if j not in project_links:
|
||||
project_links.append(j)
|
||||
|
||||
with open("links.json", "w") as f:
|
||||
json.dump(project_links, f)
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
|
||||
options = Options()
|
||||
#options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
driver = webdriver.Chrome(options=options)
|
||||
config = read_config("links_config.json")
|
||||
project_links = getLinks(driver,config)
|
||||
|
||||
print("Number of projects: " + str(len(project_links)))
|
||||
|
||||
write_links(project_links)
|
||||
|
||||
driver.close()
|
||||
|
||||
print("Finished")
|
||||
Vendored
+210
@@ -0,0 +1,210 @@
|
||||
from elasticsearch import Elasticsearch, helpers
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
es = Elasticsearch('https://inse.nes.uni-due.de:443/elastic', basic_auth=('elastic', 'RLldUaJgbGeoqd3KCX3p'), request_timeout=60, max_retries=5, retry_on_timeout=True)
|
||||
index_name = "dfg_projects_all_test"
|
||||
|
||||
def load_log(log_name="uploaded.json"):
|
||||
if os.path.exists(log_name):
|
||||
with open(log_name, 'r') as f:
|
||||
return json.load(f)
|
||||
log = {"done": [], "failed": []}
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
return log
|
||||
|
||||
def save_log(log, log_name="uploaded.json"):
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Elasticsearch helpers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def check_elastic_index(data_names, index_name):
|
||||
if es.indices.exists(index=index_name):
|
||||
return
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"searchabilityAnalyzer": {
|
||||
"type": "custom", "tokenizer": "standard",
|
||||
"filter": ["lowercase", "asciifolding"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
properties = {}
|
||||
for name in data_names:
|
||||
if name in ("funding_start", "funding_end"):
|
||||
properties[name] = {"type": "integer"}
|
||||
elif name in ("current_projects"):
|
||||
properties[name] = {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"project_id": {
|
||||
"type": "keyword"
|
||||
},
|
||||
"project_url": {
|
||||
"type": "keyword"
|
||||
},
|
||||
"project_title": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 1024
|
||||
}
|
||||
}
|
||||
},
|
||||
"meta_raw": {
|
||||
"type": "text"
|
||||
},
|
||||
"teilprojektleiter": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword"
|
||||
}
|
||||
}
|
||||
},
|
||||
"id": {
|
||||
"type": "keyword"
|
||||
},
|
||||
"url": {
|
||||
"type": "keyword"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
elif name in ("project_results_publications"):
|
||||
properties[name]={
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 1024
|
||||
}
|
||||
}
|
||||
},
|
||||
"url": {
|
||||
"type": "keyword"
|
||||
},
|
||||
"authors_raw": {
|
||||
"type": "text"
|
||||
},
|
||||
"meta_raw": {
|
||||
"type": "text"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else:
|
||||
properties[name] = {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {"keyword": {"type": "keyword", "ignore_above": 256}}
|
||||
}
|
||||
es.indices.create(index=index_name, mappings={"properties": properties}, settings=settings)
|
||||
|
||||
def check_elastic_online():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
|
||||
from elasticsearch import helpers
|
||||
import json
|
||||
|
||||
def upload_projects(data_list, index_name, log, chunk_size=500):
|
||||
"""Chunked bulk upload with safe logging."""
|
||||
|
||||
def chunkify(lst, size):
|
||||
for i in range(0, len(lst), size):
|
||||
yield lst[i:i + size]
|
||||
|
||||
total_success = 0
|
||||
|
||||
for chunk_idx, chunk in enumerate(chunkify(data_list, chunk_size)):
|
||||
actions = []
|
||||
|
||||
for doc in chunk:
|
||||
link = doc.get("link")
|
||||
|
||||
# skip already done
|
||||
if link in log["done"]:
|
||||
continue
|
||||
|
||||
actions.append({
|
||||
"_index": index_name,
|
||||
"_id": link,
|
||||
"_source": doc
|
||||
})
|
||||
|
||||
if not actions:
|
||||
continue
|
||||
|
||||
print(f"\nUploading chunk {chunk_idx + 1} ({len(actions)} docs)...")
|
||||
|
||||
try:
|
||||
success, errors = helpers.bulk(
|
||||
es,
|
||||
actions,
|
||||
raise_on_error=False,
|
||||
stats_only=False
|
||||
)
|
||||
|
||||
total_success += success
|
||||
|
||||
for action in actions:
|
||||
log["done"].append(action["_id"])
|
||||
|
||||
print(f"Chunk {chunk_idx + 1}: {success} indexed")
|
||||
|
||||
|
||||
if errors:
|
||||
print(f"Chunk {chunk_idx + 1}: some failures")
|
||||
for err in errors:
|
||||
try:
|
||||
failed_id = err["index"]["_id"]
|
||||
log["failed"].append(failed_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
print(f"Chunk {chunk_idx + 1} failed completely: {e}")
|
||||
for action in actions:
|
||||
log["failed"].append(action["_id"])
|
||||
|
||||
save_log(log)
|
||||
|
||||
print(f"\nDONE. Total indexed: {total_success}")
|
||||
if __name__ == "__main__":
|
||||
|
||||
check_elastic_online()
|
||||
|
||||
data_file = "data.json"
|
||||
if not os.path.exists(data_file):
|
||||
print(f"Error: {data_file} not found in current directory.")
|
||||
sys.exit(1)
|
||||
|
||||
with open(data_file, "r", encoding="utf-8") as f:
|
||||
projects = json.load(f)
|
||||
|
||||
all_field_names = set()
|
||||
for item in projects:
|
||||
all_field_names.update(item.keys())
|
||||
|
||||
check_elastic_index(list(all_field_names), index_name)
|
||||
|
||||
log = load_log()
|
||||
|
||||
upload_projects(projects, index_name,log)
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"start_url_1":"https://gepris.dfg.de/gepris/OCTOPUS?beginOfFunding=&bewilligungsStatus=&bundesland=DEU%23&context=projekt&einrichtungsart=-1&fachgebiet=%23&findButton=historyCall&gefoerdertIn=&ggsHunderter=0&hitsPerPage=50&index=",
|
||||
"start_url_2":"&nurProjekteMitAB=false&oldGgsHunderter=0&oldfachgebiet=%23&orderBy=gz&pemu=%23&task=doKatalog&teilprojekte=true&zk_transferprojekt=false",
|
||||
"results_header":"/html/body/div[1]/div/div[3]/div[1]/div/div/h1",
|
||||
"no_results":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[2]/div/p",
|
||||
"cookies":"//*[@id='c-s-bn']",
|
||||
"link_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[1]/div/div[2]/div[3]/div[",
|
||||
"link_2":"]/div[1]/h2/a"
|
||||
}
|
||||
Vendored
Vendored
+131
@@ -0,0 +1,131 @@
|
||||
import json
|
||||
|
||||
TEXT_KEYWORD = {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
KEYWORD_ONLY = {"type": "keyword"}
|
||||
|
||||
TYPE_MAP = {
|
||||
bool: {"type": "boolean"},
|
||||
int: {"type": "long"},
|
||||
float: {"type": "double"},
|
||||
}
|
||||
|
||||
|
||||
def infer_scalar(value):
|
||||
"""Map a Python scalar to an ES field definition."""
|
||||
# bool must come before int (bool is subclass of int)
|
||||
for py_type, es_type in TYPE_MAP.items():
|
||||
if isinstance(value, py_type):
|
||||
return es_type
|
||||
return TEXT_KEYWORD
|
||||
|
||||
|
||||
def infer_object(d):
|
||||
"""Infer properties from a dict — always flat object, never nested."""
|
||||
return {k: infer(v) for k, v in d.items()}
|
||||
|
||||
|
||||
def infer(value):
|
||||
"""
|
||||
Infer an ES field definition from a Python value.
|
||||
- dict → object with properties (flat, not nested)
|
||||
- list of dicts → nested with merged properties
|
||||
- list of scalars → scalar type of first non-None element
|
||||
- scalar → typed field
|
||||
- empty list → None (skip; can't infer)
|
||||
"""
|
||||
if isinstance(value, dict):
|
||||
props = infer_object(value)
|
||||
return {"properties": props} # object mapping, no "type" = ES object
|
||||
|
||||
if isinstance(value, list):
|
||||
if not value:
|
||||
return None # can't infer from empty list
|
||||
|
||||
# List of dicts → nested
|
||||
dict_items = [i for i in value if isinstance(i, dict)]
|
||||
if dict_items:
|
||||
props = {}
|
||||
for item in dict_items:
|
||||
props = merge_props(props, infer_object(item))
|
||||
return {"type": "nested", "properties": props}
|
||||
|
||||
# List of scalars → infer from first non-None
|
||||
for item in value:
|
||||
if item is not None:
|
||||
return infer_scalar(item)
|
||||
return None # all None, can't infer
|
||||
|
||||
if value is None:
|
||||
return None # skip null fields
|
||||
|
||||
return infer_scalar(value)
|
||||
|
||||
|
||||
def merge_props(a, b):
|
||||
"""
|
||||
Merge two ES properties dicts.
|
||||
- New keys from b are added.
|
||||
- Conflicting keys: if both are object/nested, recurse.
|
||||
- Conflicting keys: if types differ, prefer the wider type (text > keyword, nested > object).
|
||||
"""
|
||||
result = dict(a)
|
||||
|
||||
for key, b_val in b.items():
|
||||
if b_val is None:
|
||||
continue
|
||||
|
||||
if key not in result:
|
||||
result[key] = b_val
|
||||
continue
|
||||
|
||||
a_val = result[key]
|
||||
|
||||
# Both are nested → merge their properties
|
||||
if a_val.get("type") == "nested" and b_val.get("type") == "nested":
|
||||
result[key] = {
|
||||
"type": "nested",
|
||||
"properties": merge_props(
|
||||
a_val.get("properties", {}),
|
||||
b_val.get("properties", {})
|
||||
)
|
||||
}
|
||||
# Both are objects (no "type" key, just "properties")
|
||||
elif "properties" in a_val and "properties" in b_val:
|
||||
result[key] = {
|
||||
"properties": merge_props(
|
||||
a_val["properties"],
|
||||
b_val["properties"]
|
||||
)
|
||||
}
|
||||
# Type conflict: one is nested/object, other is scalar → warn and keep wider
|
||||
elif a_val.get("type") != b_val.get("type"):
|
||||
print(f"[WARN] Type conflict on '{key}': {a_val.get('type')!r} vs {b_val.get('type')!r} — keeping first")
|
||||
# Same type: keep as-is
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def create_mapping(filename):
|
||||
with open(filename) as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Support both a list of docs and a single doc
|
||||
docs = data if isinstance(data, list) else [data]
|
||||
|
||||
properties = {}
|
||||
for doc in docs:
|
||||
if not isinstance(doc, dict):
|
||||
continue
|
||||
inferred = infer_object(doc)
|
||||
properties = merge_props(properties, inferred)
|
||||
|
||||
return {"properties": properties}
|
||||
+1
File diff suppressed because one or more lines are too long
+13
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"title":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/h1",
|
||||
"cookies":"//*[@id='c-s-bn']",
|
||||
"extend_elements":"html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]//ins[@class='jstree-icon']",
|
||||
"institution_name":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/h1",
|
||||
"institution_projects":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[3]/div[1]/ul",
|
||||
"underlying_insts":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[5]/div[1]/ul",
|
||||
"institution_meta_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/div/p[",
|
||||
"institution_meta_2":"]",
|
||||
"institution_metadata":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]",
|
||||
"institution_content_frames":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[contains(@class, 'content_frame')]",
|
||||
"institution_content_frames_headers":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[contains(@class, 'PDFViewFix')]/ul/li/a"
|
||||
}
|
||||
+461
@@ -0,0 +1,461 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException, WebDriverException, TimeoutException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
from elasticsearch import Elasticsearch
|
||||
|
||||
DEFAULT_WAIT_TIMEOUT = 15
|
||||
SHORT_WAIT_TIMEOUT = 10
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Utilities
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def normalize_key(raw_key):
|
||||
return raw_key.lower().replace("-", " ").replace(" ", "_") if raw_key else "unknown_label"
|
||||
|
||||
def get_id(url):
|
||||
if len(url.split("/")) < 1:
|
||||
return ""
|
||||
return url.split("/")[-1]
|
||||
|
||||
def parse_name(raw: str) -> str:
|
||||
name = raw.replace("\n", " ").strip()
|
||||
parts = name.split(", ", 1)
|
||||
return f"{parts[1]} {parts[0]}" if len(parts) == 2 else name
|
||||
|
||||
def does_elem_exist(driver, xpath):
|
||||
try:
|
||||
driver.find_element(By.XPATH, xpath)
|
||||
return True
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
|
||||
def safe_get_text_from_xpath(driver, xpath, timeout=SHORT_WAIT_TIMEOUT):
|
||||
try:
|
||||
element = WebDriverWait(driver, timeout).until(
|
||||
EC.presence_of_element_located((By.XPATH, xpath))
|
||||
)
|
||||
text = element.text.replace("\n", " ").strip()
|
||||
return text if text else ""
|
||||
except (TimeoutException, NoSuchElementException, WebDriverException):
|
||||
return ""
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Log helpers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def load_log(log_name="dfg_data_crawler_log.json"):
|
||||
if os.path.exists(log_name):
|
||||
with open(log_name, 'r') as f:
|
||||
return json.load(f)
|
||||
log = {"done": [], "failed": []}
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
return log
|
||||
|
||||
def save_log(log, log_name="dfg_data_crawler_log.json"):
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Page setup
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def load_page(driver, url, config):
|
||||
"""Navigate to URL and wait for title element. Retries once on timeout."""
|
||||
driver.get(url)
|
||||
try:
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["institution_name"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print(f"Timeout on {url}, retrying...")
|
||||
driver.get(url)
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["institution_name"]))
|
||||
)
|
||||
|
||||
def accept_cookies(driver, config):
|
||||
try:
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.element_to_be_clickable((By.XPATH, config["cookies"]))
|
||||
).click()
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
def expand_all_elements(driver, config):
|
||||
for e in driver.find_elements(By.XPATH, config["extend_elements"]):
|
||||
try:
|
||||
e.click()
|
||||
except:
|
||||
pass
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Metadata block scraper (shared pattern)
|
||||
# ─────────────────────────────────────────────
|
||||
def scrape_metadata_block(driver, data, data_names, path_prefix_1, path_prefix_2, start=1, label_prefix=""):
|
||||
"""
|
||||
Iterates over span-based metadata rows (label in span[1], value in span[2]).
|
||||
Optionally prefixes keys with label_prefix (e.g. 'project_results_').
|
||||
Stores anchor data as nested list of objects: [{"text": ..., "id": ..., "url": ...}]
|
||||
"""
|
||||
counter = start
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
while does_elem_exist(driver, elem_path):
|
||||
try:
|
||||
raw_label = safe_get_text_from_xpath(driver, elem_path + "/span[1]")
|
||||
label = label_prefix + normalize_key(raw_label)
|
||||
|
||||
if label:
|
||||
if label not in data_names:
|
||||
data_names.append(label)
|
||||
|
||||
anchors = driver.find_elements(By.XPATH, elem_path + "/span[2]/a")
|
||||
if anchors:
|
||||
data[label] = [
|
||||
{
|
||||
"text": a.text,
|
||||
"id": get_id(a.get_attribute("href")),
|
||||
"url": a.get_attribute("href"),
|
||||
}
|
||||
for a in anchors
|
||||
]
|
||||
else:
|
||||
data[label] = safe_get_text_from_xpath(driver, elem_path + "/span[2]")
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
counter += 1
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
def scrape_institution_details_block(driver, data, data_names, path_prefix_1, path_prefix_2, start=1, label_prefix=""):
|
||||
"""
|
||||
Iterates over span-based metadata rows (label in span[1], value in span[2]).
|
||||
Optionally prefixes keys with label_prefix (e.g. 'institution_results_').
|
||||
"""
|
||||
counter = start
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
while does_elem_exist(driver, elem_path):
|
||||
try:
|
||||
raw_label = safe_get_text_from_xpath(driver, elem_path + "/span[1]")
|
||||
label = label_prefix + normalize_key(raw_label)
|
||||
|
||||
if label:
|
||||
if label not in data_names:
|
||||
data_names.append(label)
|
||||
data[label] = safe_get_text_from_xpath(driver, elem_path + "/span[2]")
|
||||
|
||||
# collect anchor urls inside span[2]
|
||||
anchors = driver.find_elements(By.XPATH, elem_path + "/span[2]/a")
|
||||
if anchors:
|
||||
ids = [get_id(a.get_attribute('href')) for a in anchors]
|
||||
urls = [a.get_attribute('href') for a in anchors]
|
||||
for key, val in [(label + "_ids", ids), (label + "_urls", urls)]:
|
||||
if key not in data_names:
|
||||
data_names.append(key)
|
||||
data[key] = val
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
counter += 1
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Section scrapers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_institution_details(driver, data, data_names, config):
|
||||
"""Scrape name/metadata, then navigate back."""
|
||||
print("Fetching institution details")
|
||||
try:
|
||||
#institution details
|
||||
if does_elem_exist(driver,config["institution_metadata"]):
|
||||
data["name"] = safe_get_text_from_xpath(driver, config["institution_name"])
|
||||
print ("META")
|
||||
scrape_metadata_block(
|
||||
driver, data, data_names,
|
||||
config["institution_meta_1"], config["institution_meta_2"],
|
||||
start=1
|
||||
)
|
||||
|
||||
if does_elem_exist(driver, config["institution_content_frames"]):
|
||||
frames = driver.find_elements(By.XPATH, config["institution_content_frames"])
|
||||
frames_headers = driver.find_elements(By.XPATH, config["institution_content_frames_headers"])
|
||||
|
||||
for i, parent_element in enumerate(frames):
|
||||
header = frames_headers[i].get_attribute("textContent").strip()
|
||||
|
||||
is_institution_frame = bool(
|
||||
parent_element.find_elements(By.XPATH, "./div[starts-with(@id,'untergeordneteInstitutionen')]")
|
||||
)
|
||||
is_projects_frame = bool(
|
||||
parent_element.find_elements(By.XPATH, "./div[starts-with(@id,'beteiligungen-main')]")
|
||||
)
|
||||
root_lis = parent_element.find_elements(
|
||||
By.XPATH, "./div/ul/li"
|
||||
)
|
||||
|
||||
if not root_lis:
|
||||
print(f"[WARN] No root <li> found in frame: {header}")
|
||||
continue
|
||||
|
||||
if is_institution_frame:
|
||||
data["underlying_institutions"] = [walk_institution(li) for li in root_lis]
|
||||
elif is_projects_frame:
|
||||
data["projects"] = [walk_projects(li) for li in root_lis]
|
||||
|
||||
except Exception as e:
|
||||
print(f"Institution metadata error: {e}")
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Walkers (recursive institution metadata)
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def extract_project(li):
|
||||
"""Extract a single project from a projectList <li>"""
|
||||
try:
|
||||
a_tag = li.find_element(By.XPATH, ".//a[contains(@class,'hrefWithNewLine')]")
|
||||
title = a_tag.get_attribute("textContent").strip()
|
||||
url = a_tag.get_attribute("href").strip()
|
||||
except NoSuchElementException:
|
||||
return None
|
||||
|
||||
persons = []
|
||||
for person_a in li.find_elements(By.XPATH, ".//div[contains(@style,'padding-top')]//a[contains(@class,'intern')]"):
|
||||
persons.append({
|
||||
"name": person_a.get_attribute("textContent").strip(),
|
||||
"id": get_id(person_a.get_attribute("href")),
|
||||
"url": person_a.get_attribute("href").strip(),
|
||||
})
|
||||
|
||||
return {
|
||||
"title": title,
|
||||
"id": get_id(url),
|
||||
"url": url,
|
||||
"persons": persons,
|
||||
}
|
||||
|
||||
|
||||
def walk_projects(li):
|
||||
"""
|
||||
Walks: program_li > status_li > ul.projectList
|
||||
Returns:
|
||||
{
|
||||
"role": "Sonderforschungsbereiche",
|
||||
"children": [
|
||||
{
|
||||
"role": "laufende Projekte",
|
||||
"children": [ { "title": ..., "id": ..., "url": ..., "persons": [...] } ]
|
||||
}
|
||||
]
|
||||
}
|
||||
"""
|
||||
try:
|
||||
role = li.find_element(By.XPATH, "./a").get_attribute("textContent").strip()
|
||||
except NoSuchElementException:
|
||||
role = "unknown"
|
||||
|
||||
project_lis = li.find_elements(By.XPATH, "./ul[contains(@class,'projectList')]/li")
|
||||
if project_lis:
|
||||
projects = [p for li_ in project_lis if (p := extract_project(li_)) is not None]
|
||||
return {
|
||||
"role": role,
|
||||
"children": projects,
|
||||
}
|
||||
|
||||
children = [
|
||||
walk_projects(child_li)
|
||||
for child_li in li.find_elements(By.XPATH, "./ul/li")
|
||||
]
|
||||
|
||||
return {
|
||||
"role": role,
|
||||
"children": children,
|
||||
}
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Walker 2: Institutions
|
||||
# Structure: institution_li > ul.innerInstList > institution_li > ...
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def walk_institution(li):
|
||||
"""
|
||||
Walks: institution_li > ul.innerInstList > institution_li (recursive)
|
||||
Returns:
|
||||
{
|
||||
"role": "Fakultät für Sozialwissenschaften",
|
||||
"id": "14150",
|
||||
"url": "/gepris/institution/14150",
|
||||
"children": [ ... ]
|
||||
}
|
||||
"""
|
||||
try:
|
||||
a_tag = li.find_element(By.XPATH, "./a")
|
||||
role = a_tag.get_attribute("textContent").strip()
|
||||
url = a_tag.get_attribute("href").strip()
|
||||
node_id = get_id(url)
|
||||
except NoSuchElementException:
|
||||
role, url, node_id = "unknown", None, None
|
||||
|
||||
children = [
|
||||
walk_institution(child_li)
|
||||
for child_li in li.find_elements(By.XPATH, "./ul[contains(@class,'innerInstList')]/li")
|
||||
]
|
||||
|
||||
return {
|
||||
"role": role,
|
||||
"id": node_id,
|
||||
"url": url,
|
||||
"children": children,
|
||||
}
|
||||
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Main pipeline
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_institution(driver, url, config, data_names):
|
||||
"""Scrape a single institution page. Returns data dict or None on failure."""
|
||||
data = {
|
||||
"url": url,
|
||||
"id": url[url.rfind("/") + 1:]
|
||||
}
|
||||
|
||||
# 1. Load page
|
||||
load_page(driver, url, config)
|
||||
|
||||
# 2. Accept cookies (only fires once, then silently skipped)
|
||||
accept_cookies(driver, config)
|
||||
print("Cookies accepted")
|
||||
# 3. Expand collapsed sections
|
||||
expand_all_elements(driver, config)
|
||||
print("Expanded")
|
||||
# 4. Scrapte basic infos
|
||||
# 5 Click through to institution page and scrape details
|
||||
scrape_institution_details(driver=driver, data=data,data_names=data_names, config=config)
|
||||
|
||||
return data
|
||||
|
||||
import json
|
||||
from collections import deque
|
||||
|
||||
def institution_level(driver, urls_to_process, urls_mapping, config):
|
||||
log = load_log()
|
||||
data_names = ["id", "url"]
|
||||
data_list = []
|
||||
|
||||
# visited prevents duplicates across primary + secondary
|
||||
visited = set(log.get("done", []))
|
||||
|
||||
# build primary -> secondary lookup
|
||||
primary_to_secondary = {a: b for a, b in urls_mapping}
|
||||
|
||||
# queue with metadata
|
||||
queue = deque([
|
||||
{"url": u, "parent": None} for u in urls_to_process
|
||||
])
|
||||
|
||||
while queue:
|
||||
item = queue.popleft()
|
||||
url = item["url"]
|
||||
parent = item["parent"]
|
||||
|
||||
print(f"Processing: {url} (parent: {parent})")
|
||||
|
||||
if url in visited:
|
||||
print(" Already processed, skipping.")
|
||||
continue
|
||||
|
||||
try:
|
||||
data = scrape_institution(driver, url, config, data_names)
|
||||
|
||||
data["url"] = url
|
||||
data["child_url"] = primary_to_secondary[url]
|
||||
data["parent_url"] = parent # track relationship
|
||||
data_list.append(data)
|
||||
|
||||
visited.add(url)
|
||||
log["done"].append(url)
|
||||
|
||||
# enqueue secondary AFTER successful primary scrape
|
||||
if url in primary_to_secondary:
|
||||
secondary = primary_to_secondary[url]
|
||||
|
||||
if secondary not in visited:
|
||||
queue.append({
|
||||
"url": secondary,
|
||||
"parent": url
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
print(f" Failed: {e}")
|
||||
log["failed"].append(url)
|
||||
|
||||
save_log(log)
|
||||
|
||||
with open("data.json", "w", encoding="utf-8") as f:
|
||||
json.dump(data_list, f)
|
||||
# ─────────────────────────────────────────────
|
||||
# Entry point
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def read_config(path):
|
||||
with open(path, 'r') as f:
|
||||
return json.load(f)
|
||||
|
||||
def readInLinks():
|
||||
with open("links.json", "r", encoding='utf-8') as f:
|
||||
data = json.load(f)[:5]
|
||||
seen_first = set()
|
||||
urls_to_process = []
|
||||
secondary_urls_to_process = []
|
||||
urls_mapping = []
|
||||
|
||||
# collect unique pair[0]
|
||||
for a, b in data:
|
||||
if a not in seen_first:
|
||||
seen_first.add(a)
|
||||
urls_to_process.append(a)
|
||||
urls_mapping.append((a, b))
|
||||
|
||||
# now add pair[1] if not already included
|
||||
for a, b in data:
|
||||
if b not in seen_first:
|
||||
seen_first.add(b)
|
||||
secondary_urls_to_process.append(b)
|
||||
|
||||
return urls_to_process,secondary_urls_to_process, urls_mapping
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
#check_elastic_online()
|
||||
|
||||
urls_to_process, secondary_urls_to_process, urls_mapping = readInLinks()
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
driver = webdriver.Chrome(options=options)
|
||||
|
||||
print(f"Number of institutions: {len(urls_to_process)}")
|
||||
print(f"Number of secondary institutions: {len(secondary_urls_to_process)}")
|
||||
|
||||
config = read_config("data_config.json")
|
||||
institution_level(driver, urls_to_process,urls_mapping, config)
|
||||
|
||||
driver.close()
|
||||
print("Finished")
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"done": ["https://gepris.dfg.de/gepris/institution/5008", "https://gepris.dfg.de/gepris/institution/5012", "https://gepris.dfg.de/gepris/institution/10045", "https://gepris.dfg.de/gepris/institution/10047", "https://gepris.dfg.de/gepris/institution/10049"], "failed": []}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.common.exceptions import WebDriverException
|
||||
from selenium.common.exceptions import TimeoutException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from random import randint
|
||||
import time
|
||||
import sys
|
||||
from elasticsearch import Elasticsearch
|
||||
import os
|
||||
import json
|
||||
|
||||
DEFAULT_WAIT_TIMEOUT = 10
|
||||
SHORT_WAIT_TIMEOUT = 5
|
||||
|
||||
def does_elem_exist(driver, xpath):
|
||||
try:
|
||||
driver.find_element(By.XPATH, xpath)
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
return True
|
||||
|
||||
def read_config(path):
|
||||
with open(path, 'r') as jsonfile:
|
||||
config = json.load(jsonfile)
|
||||
return config
|
||||
|
||||
|
||||
def getLinks(driver,config):
|
||||
print("Starting first level.")
|
||||
project_links = []
|
||||
|
||||
log = {}
|
||||
log_name = "dfg_links_crawler_log.json"
|
||||
if os.path.exists(log_name):
|
||||
# if json exists -> read in file
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
else:
|
||||
# if json doesn't exist -> #1 create json -> #2 write in initial structure -> #3 read it in
|
||||
# 1
|
||||
open(log_name, "x")
|
||||
# 2
|
||||
initial_dict = {"done": []}
|
||||
with open(log_name, "w") as jsonfile:
|
||||
jsonfile.write(json.dumps(initial_dict))
|
||||
# 3
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
|
||||
index_counter = 0
|
||||
dfg_link_all_1 = config["start_url_1"]
|
||||
dfg_link_all_2 = config["start_url_2"]
|
||||
|
||||
while True:
|
||||
if index_counter >=50:
|
||||
break
|
||||
print(" - " + str(index_counter))
|
||||
if index_counter in log["done"]:
|
||||
print("- - Already crawled!")
|
||||
index_counter = index_counter + 50
|
||||
continue
|
||||
|
||||
dfg_link_all = dfg_link_all_1 + str(index_counter) + dfg_link_all_2
|
||||
|
||||
driver.get(dfg_link_all)
|
||||
|
||||
# Wait for the results header to be present
|
||||
try:
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["results_header"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print(f"Timeout waiting for results header on {dfg_link_all}. Continuing to next checks.")
|
||||
|
||||
# cookies
|
||||
try:
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.element_to_be_clickable((By.XPATH, config["cookies"]))
|
||||
).click()
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
# check if side exists, if not -> break loop (all links found)
|
||||
try:
|
||||
no_results_element = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["no_results"]))
|
||||
)
|
||||
text = no_results_element.text
|
||||
if text == "Ihre Suche ergab leider keine Treffer.":
|
||||
break
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
# get project_links
|
||||
# Construct a common XPath for all project links based on the config parts
|
||||
main_links_path = config["link_1"] + "*" + config["link_2"]
|
||||
secondary_links_path = config["sub_inst_link_1"] + "*" + config["sub_inst_link_2"]
|
||||
try:
|
||||
# Wait for all project links to be present and retrieve them as a list of WebElements
|
||||
main_elements = WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.XPATH, main_links_path))
|
||||
)
|
||||
secondary_elements = driver.find_elements(By.XPATH, secondary_links_path)
|
||||
|
||||
# Build a lookup of secondary hrefs by their index for safe access
|
||||
secondary_hrefs = {
|
||||
i: el.get_attribute('href')
|
||||
for i, el in enumerate(secondary_elements)
|
||||
}
|
||||
|
||||
# Extract all href attributes from the retrieved elements at once
|
||||
links = []
|
||||
for i, main_el in enumerate(main_elements):
|
||||
# entry = {
|
||||
# "main": main_el.get_attribute('href'),
|
||||
# "secondary": secondary_hrefs.get(i) # None if no matching secondary
|
||||
# }
|
||||
entry = (main_el.get_attribute('href'),secondary_hrefs.get(i))
|
||||
links.append(entry)
|
||||
|
||||
project_links.extend(links)
|
||||
print(f"Found {len(links)} person links on this page.")
|
||||
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
print("No project links found on this page within the timeout or element not found.")
|
||||
|
||||
log["done"].append(index_counter)
|
||||
index_counter = index_counter + 50
|
||||
|
||||
# write new log
|
||||
with open(log_name, "w") as outfile:
|
||||
outfile.write(json.dumps(log))
|
||||
write_links(project_links=project_links)
|
||||
return project_links
|
||||
|
||||
def write_links(project_links):
|
||||
print(len(project_links))
|
||||
js = []
|
||||
if os.path.exists("links.json"):
|
||||
with open("links.json", 'r') as jsonfile:
|
||||
js = json.load(jsonfile)
|
||||
|
||||
for j in js:
|
||||
if j not in project_links:
|
||||
project_links.append(j)
|
||||
|
||||
with open("links.json", "w") as f:
|
||||
json.dump(project_links, f)
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
driver = webdriver.Chrome(options=options)
|
||||
config = read_config("links_config.json")
|
||||
project_links = getLinks(driver,config)
|
||||
|
||||
print("Number of persons: " + str(len(project_links)))
|
||||
|
||||
#write_links(project_links)
|
||||
|
||||
driver.close()
|
||||
|
||||
print("Finished")
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"done": [0]}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
from elasticsearch import Elasticsearch, helpers
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
|
||||
from build_mapping import create_mapping
|
||||
es = Elasticsearch('https://inse.nes.uni-due.de:443/elastic', basic_auth=('elastic', 'RLldUaJgbGeoqd3KCX3p'), request_timeout=60, max_retries=5, retry_on_timeout=True)
|
||||
index_name = "dfg_insts_all_test"
|
||||
|
||||
def load_log(log_name="uploaded.json"):
|
||||
if os.path.exists(log_name):
|
||||
with open(log_name, 'r') as f:
|
||||
return json.load(f)
|
||||
log = {"done": [], "failed": []}
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
return log
|
||||
|
||||
def save_log(log, log_name="uploaded.json"):
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Elasticsearch helpers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def check_elastic_index(data_names, index_name, nested_field_names=None):
|
||||
if es.indices.exists(index=index_name):
|
||||
return
|
||||
|
||||
nested_field_names = nested_field_names or set()
|
||||
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"searchabilityAnalyzer": {
|
||||
"type": "custom", "tokenizer": "standard",
|
||||
"filter": ["lowercase", "asciifolding"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# def text_keyword(ignore_above=256):
|
||||
# return {
|
||||
# "type": "text",
|
||||
# "analyzer": "searchabilityAnalyzer",
|
||||
# "search_analyzer": "searchabilityAnalyzer",
|
||||
# "fields": {"keyword": {"type": "keyword", "ignore_above": ignore_above}}
|
||||
# }
|
||||
|
||||
# keyword = {"type": "keyword"}
|
||||
|
||||
# properties = {}
|
||||
# for name in data_names:
|
||||
# if name in ("funding_start", "funding_end"):
|
||||
# properties[name] = {"type": "integer"}
|
||||
|
||||
# elif name == "orcid_id":
|
||||
# properties[name] = {
|
||||
# "type": "nested",
|
||||
# "properties": {
|
||||
# "text": text_keyword(),
|
||||
# "id": keyword,
|
||||
# "url": keyword,
|
||||
# }
|
||||
# }
|
||||
|
||||
# elif name in nested_field_names:
|
||||
# properties[name] = {
|
||||
# "type": "nested",
|
||||
# "properties": {
|
||||
# "title": text_keyword(),
|
||||
# "id": keyword,
|
||||
# "url": keyword,
|
||||
# "category": keyword,
|
||||
# "type" :text_keyword()
|
||||
# }
|
||||
# }
|
||||
|
||||
# else:
|
||||
# properties[name] = text_keyword()
|
||||
mappings = create_mapping("data.json")
|
||||
es.indices.create(index=index_name, mappings=mappings, settings=settings)
|
||||
|
||||
|
||||
def check_elastic_online():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
|
||||
from elasticsearch import helpers
|
||||
import json
|
||||
|
||||
def upload_projects(data_list, index_name, log, chunk_size=500):
|
||||
"""Chunked bulk upload with safe logging."""
|
||||
|
||||
def chunkify(lst, size):
|
||||
for i in range(0, len(lst), size):
|
||||
yield lst[i:i + size]
|
||||
|
||||
total_success = 0
|
||||
|
||||
for chunk_idx, chunk in enumerate(chunkify(data_list, chunk_size)):
|
||||
actions = []
|
||||
|
||||
for doc in chunk:
|
||||
link = doc.get("link")
|
||||
id = doc.get("id")
|
||||
# skip already done
|
||||
if link in log["done"]:
|
||||
continue
|
||||
|
||||
actions.append({
|
||||
"_index": index_name,
|
||||
"_id": id,
|
||||
"_source": doc
|
||||
})
|
||||
|
||||
if not actions:
|
||||
continue
|
||||
|
||||
print(f"\nUploading chunk {chunk_idx + 1} ({len(actions)} docs)...")
|
||||
|
||||
try:
|
||||
success, errors = helpers.bulk(
|
||||
es,
|
||||
actions,
|
||||
raise_on_error=False,
|
||||
stats_only=False
|
||||
)
|
||||
|
||||
total_success += success
|
||||
|
||||
for action in actions:
|
||||
log["done"].append(action["_id"])
|
||||
|
||||
print(f"Chunk {chunk_idx + 1}: {success} indexed")
|
||||
|
||||
|
||||
if errors:
|
||||
print(f"Chunk {chunk_idx + 1}: some failures")
|
||||
for err in errors:
|
||||
try:
|
||||
failed_id = err["index"]["_id"]
|
||||
log["failed"].append(failed_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
print(f"Chunk {chunk_idx + 1} failed completely: {e}")
|
||||
for action in actions:
|
||||
log["failed"].append(action["_id"])
|
||||
|
||||
save_log(log)
|
||||
|
||||
print(f"\nDONE. Total indexed: {total_success}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
check_elastic_online()
|
||||
|
||||
data_file = "data.json"
|
||||
if not os.path.exists(data_file):
|
||||
print(f"Error: {data_file} not found in current directory.")
|
||||
sys.exit(1)
|
||||
|
||||
with open(data_file, "r", encoding="utf-8") as f:
|
||||
projects = json.load(f)
|
||||
|
||||
all_field_names = set()
|
||||
nested_field_names = set()
|
||||
|
||||
for item in projects:
|
||||
all_field_names.update(item.keys())
|
||||
for key, value in item.items():
|
||||
if (
|
||||
isinstance(value, list)
|
||||
and value
|
||||
and isinstance(value[0], dict)
|
||||
):
|
||||
nested_field_names.add(key)
|
||||
|
||||
check_elastic_index(list(all_field_names), index_name, nested_field_names)
|
||||
|
||||
log = load_log()
|
||||
|
||||
upload_projects(projects, index_name,log)
|
||||
+1
File diff suppressed because one or more lines are too long
+11
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"start_url_1":"https://gepris.dfg.de/gepris/OCTOPUS?beginOfFunding=&bewilligungsStatus=&bundesland=DEU%23&context=institution&einrichtungsart=-1&fachgebiet=%23&findButton=historyCall&gefoerdertIn=&ggsHunderter=0&hitsPerPage=50&index=",
|
||||
"start_url_2":"&nurProjekteMitAB=false&oldGgsHunderter=0&oldfachgebiet=%23&orderBy=gz&pemu=%23&task=doKatalog&teilprojekte=true&zk_transferprojekt=false",
|
||||
"results_header":"/html/body/div[1]/div/div[3]/div[1]/div/div/h1",
|
||||
"no_results":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[2]/div/p",
|
||||
"cookies":"//*[@id='c-s-bn']",
|
||||
"link_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[1]/div/div[2]/div[3]/div[",
|
||||
"link_2":"]/div[1]/h2/a",
|
||||
"sub_inst_link_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[1]/div/div[2]/div[3]/div[",
|
||||
"sub_inst_link_2":"]/div[2]/a"
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"done": ["5008", "5012", "10045", "10047", "10049", "5008", "5012", "10045", "10047", "10049"], "failed": ["10045", "10047", "10049"]}
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
+11
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"title":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/h1",
|
||||
"cookies":"//*[@id='c-s-bn']",
|
||||
"extend_elements":"html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]//ins[@class='jstree-icon']",
|
||||
"person_link":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/div[1]/span[2]/a",
|
||||
"person_name":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/h1",
|
||||
"person_projects_frame":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[contains(@class, 'content_frame')]",
|
||||
"person_meta_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/p[",
|
||||
"person_meta_2":"]",
|
||||
"person_metadata":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]"
|
||||
}
|
||||
+373
@@ -0,0 +1,373 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException, WebDriverException, TimeoutException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
from elasticsearch import Elasticsearch
|
||||
|
||||
DEFAULT_WAIT_TIMEOUT = 15
|
||||
SHORT_WAIT_TIMEOUT = 10
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Utilities
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def normalize_key(raw_key):
|
||||
return raw_key.lower().replace("-", " ").replace(" ", "_")
|
||||
|
||||
def get_id(url):
|
||||
return url.split("/")[-1]
|
||||
|
||||
def parse_name(raw: str) -> str:
|
||||
name = raw.replace("\n", " ").strip()
|
||||
parts = name.split(", ", 1)
|
||||
return f"{parts[1]} {parts[0]}" if len(parts) == 2 else name
|
||||
|
||||
def does_elem_exist(driver, xpath):
|
||||
try:
|
||||
driver.find_element(By.XPATH, xpath)
|
||||
return True
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
|
||||
def safe_get_text_from_xpath(driver, xpath, timeout=SHORT_WAIT_TIMEOUT):
|
||||
try:
|
||||
element = WebDriverWait(driver, timeout).until(
|
||||
EC.presence_of_element_located((By.XPATH, xpath))
|
||||
)
|
||||
text = element.text.replace("\n", " ").strip()
|
||||
return text if text else ""
|
||||
except (TimeoutException, NoSuchElementException, WebDriverException):
|
||||
return ""
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Log helpers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def load_log(log_name="dfg_data_crawler_log.json"):
|
||||
if os.path.exists(log_name):
|
||||
with open(log_name, 'r') as f:
|
||||
return json.load(f)
|
||||
log = {"done": [], "failed": []}
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
return log
|
||||
|
||||
def save_log(log, log_name="dfg_data_crawler_log.json"):
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Page setup
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def load_page(driver, url, config):
|
||||
"""Navigate to URL and wait for title element. Retries once on timeout."""
|
||||
driver.get(url)
|
||||
try:
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["person_name"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print(f"Timeout on {url}, retrying...")
|
||||
driver.get(url)
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["person_name"]))
|
||||
)
|
||||
|
||||
def accept_cookies(driver, config):
|
||||
try:
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.element_to_be_clickable((By.XPATH, config["cookies"]))
|
||||
).click()
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
def expand_all_elements(driver, config):
|
||||
for e in driver.find_elements(By.XPATH, config["extend_elements"]):
|
||||
try:
|
||||
e.click()
|
||||
except:
|
||||
pass
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Metadata block scraper (shared pattern)
|
||||
# ─────────────────────────────────────────────
|
||||
def scrape_metadata_block(driver, data, data_names, path_prefix_1, path_prefix_2, start=1, label_prefix=""):
|
||||
"""
|
||||
Iterates over span-based metadata rows (label in span[1], value in span[2]).
|
||||
Optionally prefixes keys with label_prefix (e.g. 'project_results_').
|
||||
Stores anchor data as nested list of objects: [{"text": ..., "id": ..., "url": ...}]
|
||||
"""
|
||||
counter = start
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
while does_elem_exist(driver, elem_path):
|
||||
try:
|
||||
raw_label = safe_get_text_from_xpath(driver, elem_path + "/span[1]")
|
||||
label = label_prefix + normalize_key(raw_label)
|
||||
|
||||
if label:
|
||||
if label not in data_names:
|
||||
data_names.append(label)
|
||||
|
||||
anchors = driver.find_elements(By.XPATH, elem_path + "/span[2]/a")
|
||||
if anchors:
|
||||
data[label] = [
|
||||
{
|
||||
"text": a.text,
|
||||
"id": get_id(a.get_attribute("href")),
|
||||
"url": a.get_attribute("href"),
|
||||
}
|
||||
for a in anchors
|
||||
]
|
||||
else:
|
||||
data[label] = safe_get_text_from_xpath(driver, elem_path + "/span[2]")
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
counter += 1
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
def scrape_person_details_block(driver, data, data_names, path_prefix_1, path_prefix_2, start=1, label_prefix=""):
|
||||
"""
|
||||
Iterates over span-based metadata rows (label in span[1], value in span[2]).
|
||||
Optionally prefixes keys with label_prefix (e.g. 'person_results_').
|
||||
"""
|
||||
counter = start
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
while does_elem_exist(driver, elem_path):
|
||||
try:
|
||||
raw_label = safe_get_text_from_xpath(driver, elem_path + "/span[1]")
|
||||
label = label_prefix + normalize_key(raw_label)
|
||||
|
||||
if label:
|
||||
if label not in data_names:
|
||||
data_names.append(label)
|
||||
data[label] = safe_get_text_from_xpath(driver, elem_path + "/span[2]")
|
||||
|
||||
# collect anchor urls inside span[2]
|
||||
anchors = driver.find_elements(By.XPATH, elem_path + "/span[2]/a")
|
||||
if anchors:
|
||||
ids = [get_id(a.get_attribute('href')) for a in anchors]
|
||||
urls = [a.get_attribute('href') for a in anchors]
|
||||
for key, val in [(label + "_ids", ids), (label + "_urls", urls)]:
|
||||
if key not in data_names:
|
||||
data_names.append(key)
|
||||
data[key] = val
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
counter += 1
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Section scrapers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_person_details(driver, data, data_names, config):
|
||||
"""Scrape name/metadata, then navigate back."""
|
||||
print("Fetching person details")
|
||||
try:
|
||||
#person details
|
||||
if does_elem_exist(driver,config["person_metadata"]):
|
||||
data["name"] = safe_get_text_from_xpath(driver, config["person_name"])
|
||||
print ("META")
|
||||
scrape_metadata_block(
|
||||
driver, data, data_names,
|
||||
config["person_meta_1"], config["person_meta_2"],
|
||||
start=1
|
||||
)
|
||||
|
||||
if does_elem_exist(driver, config["person_projects_frame"]):
|
||||
frames = driver.find_elements(By.XPATH, config["person_projects_frame"])
|
||||
|
||||
for i, parent_element in enumerate(frames):
|
||||
|
||||
is_projects_frame = bool(
|
||||
parent_element.find_elements(By.XPATH, "./div[starts-with(@id,'projekteNachRolle')]")
|
||||
)
|
||||
root_lis = parent_element.find_elements(
|
||||
By.XPATH, "./div/ul/li"
|
||||
)
|
||||
|
||||
if not root_lis:
|
||||
print(f"[WARN] No root <li> found in frame: projects")
|
||||
continue
|
||||
if is_projects_frame:
|
||||
data["projects"] = [walk_projects(li) for li in root_lis]
|
||||
|
||||
except Exception as e:
|
||||
print(f"Person metadata error: {e}")
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Walk (recursive person metadata)
|
||||
# ─────────────────────────────────────────────
|
||||
def extract_project(li):
|
||||
"""
|
||||
Extract a single project from a projectList <li>.
|
||||
Handles both:
|
||||
- institution frame: a.hrefWithNewLine + persons in padding-top div
|
||||
- person frame: a.person-project-link + category as bare text
|
||||
"""
|
||||
# Try institution-style link first, then person-style
|
||||
try:
|
||||
a_tag = li.find_element(By.XPATH, ".//a[contains(@class,'hrefWithNewLine')]")
|
||||
except NoSuchElementException:
|
||||
try:
|
||||
a_tag = li.find_element(By.XPATH, ".//a[contains(@class,'person-project-link')]")
|
||||
except NoSuchElementException:
|
||||
return None
|
||||
|
||||
title = a_tag.get_attribute("textContent").strip()
|
||||
url = a_tag.get_attribute("href").strip()
|
||||
|
||||
# Persons (institution frame)
|
||||
persons = []
|
||||
for person_a in li.find_elements(By.XPATH, ".//div[contains(@style,'padding-top')]//a[contains(@class,'intern')]"):
|
||||
persons.append({
|
||||
"name": person_a.get_attribute("textContent").strip(),
|
||||
"id": get_id(person_a.get_attribute("href")),
|
||||
"url": person_a.get_attribute("href").strip(),
|
||||
})
|
||||
|
||||
# Category (person frame) — bare text sibling after the <a> inside the inner div
|
||||
category = None
|
||||
try:
|
||||
inner_div = li.find_element(By.XPATH, ".//div[a[contains(@class,'person-project-link')]]")
|
||||
full_text = inner_div.get_attribute("textContent").strip()
|
||||
project_text = title
|
||||
remainder = full_text.replace(project_text, "").strip()
|
||||
if remainder.startswith("(") and remainder.endswith(")"):
|
||||
category = remainder[1:-1].strip()
|
||||
except NoSuchElementException:
|
||||
pass
|
||||
|
||||
return {
|
||||
"title": title,
|
||||
"id": get_id(url),
|
||||
"url": url,
|
||||
"persons": persons,
|
||||
"category": category,
|
||||
}
|
||||
|
||||
|
||||
def walk_projects(li):
|
||||
"""
|
||||
Walks: role_li > status_li > ul.projectList
|
||||
Works for both frames:
|
||||
- institution: Sonderforschungsbereiche > laufende Projekte > projects
|
||||
- person: Als Antragsteller > abgeschlossene Projekte > projects
|
||||
"""
|
||||
try:
|
||||
role = li.find_element(By.XPATH, "./a").get_attribute("textContent").strip()
|
||||
except NoSuchElementException:
|
||||
role = "unknown"
|
||||
|
||||
|
||||
# Leaf: status node with a projectList
|
||||
project_lis = li.find_elements(By.XPATH, "./ul[contains(@class,'projectList')]/li")
|
||||
if project_lis:
|
||||
projects = [p for li_ in project_lis if (p := extract_project(li_)) is not None]
|
||||
return {
|
||||
"role": role,
|
||||
"children": projects,
|
||||
}
|
||||
|
||||
children = [
|
||||
walk_projects(child_li)
|
||||
for child_li in li.find_elements(By.XPATH, "./ul/li")
|
||||
]
|
||||
|
||||
return {
|
||||
"role": role,
|
||||
"children": children,
|
||||
}
|
||||
# ─────────────────────────────────────────────
|
||||
# Main pipeline
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_person(driver, url, config, data_names):
|
||||
"""Scrape a single person page. Returns data dict or None on failure."""
|
||||
data = {
|
||||
"url": url,
|
||||
"id": url[url.rfind("/") + 1:]
|
||||
}
|
||||
|
||||
# 1. Load page
|
||||
load_page(driver, url, config)
|
||||
|
||||
# 2. Accept cookies (only fires once, then silently skipped)
|
||||
accept_cookies(driver, config)
|
||||
|
||||
# 3. Expand collapsed sections
|
||||
expand_all_elements(driver, config)
|
||||
|
||||
# 4. Scrapte basic infos
|
||||
# 5 Click through to person page and scrape details
|
||||
scrape_person_details(driver=driver, data=data,data_names=data_names, config=config)
|
||||
|
||||
return data
|
||||
|
||||
def person_level(driver, person_links, config):
|
||||
log = load_log()
|
||||
data_names = ["id", "url",]
|
||||
data_list = []
|
||||
|
||||
for i, url in enumerate(person_links):
|
||||
print(f"[{i+1}/{len(person_links)}] {url}")
|
||||
|
||||
if url in log["done"]:
|
||||
print(" Already crawled, skipping.")
|
||||
continue
|
||||
|
||||
try:
|
||||
data = scrape_person(driver, url, config, data_names)
|
||||
data_list.append(data)
|
||||
log["done"].append(url)
|
||||
except Exception as e:
|
||||
print(f" Failed: {e}")
|
||||
log["failed"].append(url)
|
||||
|
||||
save_log(log)
|
||||
|
||||
with open("data.json", "w") as f:
|
||||
json.dump(data_list, f)
|
||||
# ─────────────────────────────────────────────
|
||||
# Entry point
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def read_config(path):
|
||||
with open(path, 'r') as f:
|
||||
return json.load(f)
|
||||
|
||||
def readInLinks():
|
||||
with open("links.json", "r", encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
#check_elastic_online()
|
||||
|
||||
person_links = readInLinks()[:5]
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
driver = webdriver.Chrome(options=options)
|
||||
|
||||
print(f"Number of persons: {len(person_links)}")
|
||||
config = read_config("data_config.json")
|
||||
person_level(driver, person_links, config)
|
||||
|
||||
driver.close()
|
||||
print("Finished")
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"done": ["https://gepris.dfg.de/gepris/person/5295", "https://gepris.dfg.de/gepris/person/5297", "https://gepris.dfg.de/gepris/person/5299", "https://gepris.dfg.de/gepris/person/5301", "https://gepris.dfg.de/gepris/person/5303"], "failed": []}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.common.exceptions import WebDriverException
|
||||
from selenium.common.exceptions import TimeoutException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from random import randint
|
||||
import time
|
||||
import sys
|
||||
from elasticsearch import Elasticsearch
|
||||
import os
|
||||
import json
|
||||
|
||||
DEFAULT_WAIT_TIMEOUT = 10
|
||||
SHORT_WAIT_TIMEOUT = 5
|
||||
|
||||
def does_elem_exist(driver, xpath):
|
||||
try:
|
||||
driver.find_element(By.XPATH, xpath)
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
return True
|
||||
|
||||
def read_config(path):
|
||||
with open(path, 'r') as jsonfile:
|
||||
config = json.load(jsonfile)
|
||||
return config
|
||||
|
||||
|
||||
def getLinks(driver,config):
|
||||
print("Starting first level.")
|
||||
project_links = []
|
||||
|
||||
log = {}
|
||||
log_name = "dfg_links_crawler_log.json"
|
||||
if os.path.exists(log_name):
|
||||
# if json exists -> read in file
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
else:
|
||||
# if json doesn't exist -> #1 create json -> #2 write in initial structure -> #3 read it in
|
||||
# 1
|
||||
open(log_name, "x")
|
||||
# 2
|
||||
initial_dict = {"done": []}
|
||||
with open(log_name, "w") as jsonfile:
|
||||
jsonfile.write(json.dumps(initial_dict))
|
||||
# 3
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
|
||||
index_counter = 0
|
||||
dfg_link_all_1 = config["start_url_1"]
|
||||
dfg_link_all_2 = config["start_url_2"]
|
||||
|
||||
while True:
|
||||
print(" - " + str(index_counter))
|
||||
if index_counter in log["done"]:
|
||||
print("- - Already crawled!")
|
||||
index_counter = index_counter + 50
|
||||
continue
|
||||
|
||||
dfg_link_all = dfg_link_all_1 + str(index_counter) + dfg_link_all_2
|
||||
|
||||
driver.get(dfg_link_all)
|
||||
|
||||
# Wait for the results header to be present
|
||||
try:
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["results_header"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print(f"Timeout waiting for results header on {dfg_link_all}. Continuing to next checks.")
|
||||
|
||||
# cookies
|
||||
try:
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.element_to_be_clickable((By.XPATH, config["cookies"]))
|
||||
).click()
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
# check if side exists, if not -> break loop (all links found)
|
||||
try:
|
||||
no_results_element = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["no_results"]))
|
||||
)
|
||||
text = no_results_element.text
|
||||
if text == "Ihre Suche ergab leider keine Treffer.":
|
||||
break
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
# get project_links
|
||||
# Construct a common XPath for all project links based on the config parts
|
||||
common_links_xpath = config["link_1"] + "*" + config["link_2"]
|
||||
|
||||
try:
|
||||
# Wait for all project links to be present and retrieve them as a list of WebElements
|
||||
elements = WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.XPATH, common_links_xpath))
|
||||
)
|
||||
|
||||
# Extract all href attributes from the retrieved elements at once
|
||||
links = [elem.get_attribute('href') for elem in elements if elem.get_attribute('href')]
|
||||
project_links.extend(links)
|
||||
print(f"Found {len(links)} person links on this page.")
|
||||
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
print("No project links found on this page within the timeout or element not found.")
|
||||
|
||||
log["done"].append(index_counter)
|
||||
index_counter = index_counter + 50
|
||||
|
||||
# write new log
|
||||
with open(log_name, "w") as outfile:
|
||||
outfile.write(json.dumps(log))
|
||||
write_links(project_links=project_links)
|
||||
return project_links
|
||||
|
||||
def write_links(project_links):
|
||||
print(len(project_links))
|
||||
js = []
|
||||
if os.path.exists("links.json"):
|
||||
with open("links.json", 'r') as jsonfile:
|
||||
js = json.load(jsonfile)
|
||||
|
||||
for j in js:
|
||||
if j not in project_links:
|
||||
project_links.append(j)
|
||||
|
||||
with open("links.json", "w") as f:
|
||||
json.dump(project_links, f)
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
driver = webdriver.Chrome(options=options)
|
||||
config = read_config("links_config.json")
|
||||
project_links = getLinks(driver,config)
|
||||
|
||||
print("Number of persons: " + str(len(project_links)))
|
||||
|
||||
#write_links(project_links)
|
||||
|
||||
driver.close()
|
||||
|
||||
print("Finished")
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
from elasticsearch import Elasticsearch, helpers
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
|
||||
from build_mapping import create_mapping
|
||||
|
||||
es = Elasticsearch('https://inse.nes.uni-due.de:443/elastic', basic_auth=('elastic', 'RLldUaJgbGeoqd3KCX3p'), request_timeout=60, max_retries=5, retry_on_timeout=True)
|
||||
index_name = "dfg_persons_all_test"
|
||||
|
||||
def load_log(log_name="uploaded.json"):
|
||||
if os.path.exists(log_name):
|
||||
with open(log_name, 'r') as f:
|
||||
return json.load(f)
|
||||
log = {"done": [], "failed": []}
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
return log
|
||||
|
||||
def save_log(log, log_name="uploaded.json"):
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Elasticsearch helpers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def check_elastic_index(data_names, index_name, nested_field_names=None):
|
||||
if es.indices.exists(index=index_name):
|
||||
return
|
||||
|
||||
nested_field_names = nested_field_names or set()
|
||||
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"searchabilityAnalyzer": {
|
||||
"type": "custom", "tokenizer": "standard",
|
||||
"filter": ["lowercase", "asciifolding"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# def text_keyword(ignore_above=256):
|
||||
# return {
|
||||
# "type": "text",
|
||||
# "analyzer": "searchabilityAnalyzer",
|
||||
# "search_analyzer": "searchabilityAnalyzer",
|
||||
# "fields": {"keyword": {"type": "keyword", "ignore_above": ignore_above}}
|
||||
# }
|
||||
|
||||
# keyword = {"type": "keyword"}
|
||||
|
||||
# properties = {}
|
||||
# for name in data_names:
|
||||
# if name in ("funding_start", "funding_end"):
|
||||
# properties[name] = {"type": "integer"}
|
||||
|
||||
# elif name == "orcid_id":
|
||||
# properties[name] = {
|
||||
# "type": "nested",
|
||||
# "properties": {
|
||||
# "text": text_keyword(),
|
||||
# "id": keyword,
|
||||
# "url": keyword,
|
||||
# }
|
||||
# }
|
||||
|
||||
# elif name in nested_field_names:
|
||||
# properties[name] = {
|
||||
# "type": "nested",
|
||||
# "properties": {
|
||||
# "title": text_keyword(),
|
||||
# "id": keyword,
|
||||
# "url": keyword,
|
||||
# "category": keyword,
|
||||
# "type" :text_keyword()
|
||||
# }
|
||||
# }
|
||||
|
||||
# else:
|
||||
# properties[name] = text_keyword()
|
||||
|
||||
mappings = create_mapping("data.json")
|
||||
es.indices.create(index=index_name, mappings=mappings, settings=settings)
|
||||
|
||||
|
||||
def check_elastic_online():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
|
||||
from elasticsearch import helpers
|
||||
import json
|
||||
|
||||
def upload_projects(data_list, index_name, log, chunk_size=500):
|
||||
"""Chunked bulk upload with safe logging."""
|
||||
|
||||
def chunkify(lst, size):
|
||||
for i in range(0, len(lst), size):
|
||||
yield lst[i:i + size]
|
||||
|
||||
total_success = 0
|
||||
|
||||
for chunk_idx, chunk in enumerate(chunkify(data_list, chunk_size)):
|
||||
actions = []
|
||||
|
||||
for doc in chunk:
|
||||
link = doc.get("link")
|
||||
id = doc.get("id")
|
||||
# skip already done
|
||||
if link in log["done"]:
|
||||
continue
|
||||
|
||||
actions.append({
|
||||
"_index": index_name,
|
||||
"_id": id,
|
||||
"_source": doc
|
||||
})
|
||||
|
||||
if not actions:
|
||||
continue
|
||||
|
||||
print(f"\nUploading chunk {chunk_idx + 1} ({len(actions)} docs)...")
|
||||
|
||||
try:
|
||||
success, errors = helpers.bulk(
|
||||
es,
|
||||
actions,
|
||||
raise_on_error=False,
|
||||
stats_only=False
|
||||
)
|
||||
|
||||
total_success += success
|
||||
|
||||
for action in actions:
|
||||
log["done"].append(action["_id"])
|
||||
|
||||
print(f"Chunk {chunk_idx + 1}: {success} indexed")
|
||||
|
||||
|
||||
if errors:
|
||||
print(f"Chunk {chunk_idx + 1}: some failures")
|
||||
for err in errors:
|
||||
try:
|
||||
failed_id = err["index"]["_id"]
|
||||
log["failed"].append(failed_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
print(f"Chunk {chunk_idx + 1} failed completely: {e}")
|
||||
for action in actions:
|
||||
log["failed"].append(action["_id"])
|
||||
|
||||
save_log(log)
|
||||
|
||||
print(f"\nDONE. Total indexed: {total_success}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
check_elastic_online()
|
||||
|
||||
data_file = "data.json"
|
||||
if not os.path.exists(data_file):
|
||||
print(f"Error: {data_file} not found in current directory.")
|
||||
sys.exit(1)
|
||||
|
||||
with open(data_file, "r", encoding="utf-8") as f:
|
||||
projects = json.load(f)
|
||||
|
||||
all_field_names = set()
|
||||
nested_field_names = set()
|
||||
|
||||
for item in projects:
|
||||
all_field_names.update(item.keys())
|
||||
for key, value in item.items():
|
||||
if (
|
||||
isinstance(value, list)
|
||||
and value
|
||||
and isinstance(value[0], dict)
|
||||
):
|
||||
nested_field_names.add(key)
|
||||
|
||||
check_elastic_index(list(all_field_names), index_name, nested_field_names)
|
||||
|
||||
log = load_log()
|
||||
|
||||
upload_projects(projects, index_name,log)
|
||||
extern/generic-project-crawler/project-crawler-v4-all/DFG_outdated_crawler/v1/dfg/persons/links.json
Vendored
+1
File diff suppressed because one or more lines are too long
+9
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"start_url_1":"https://gepris.dfg.de/gepris/OCTOPUS?beginOfFunding=&bewilligungsStatus=&bundesland=DEU%23&context=person&einrichtungsart=-1&fachgebiet=%23&findButton=historyCall&gefoerdertIn=&ggsHunderter=0&hitsPerPage=50&index=",
|
||||
"start_url_2":"&nurProjekteMitAB=false&oldGgsHunderter=0&oldfachgebiet=%23&orderBy=gz&pemu=%23&task=doKatalog&teilprojekte=true&zk_transferprojekt=false",
|
||||
"results_header":"/html/body/div[1]/div/div[3]/div[1]/div/div/h1",
|
||||
"no_results":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[2]/div/p",
|
||||
"cookies":"//*[@id='c-s-bn']",
|
||||
"link_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[1]/div/div[2]/div[3]/div[",
|
||||
"link_2":"]/div[1]/h2/a"
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"done": ["5295", "5297", "5299", "5301", "5303"], "failed": []}
|
||||
extern/generic-project-crawler/project-crawler-v4-all/DFG_outdated_crawler/v1/dfg/projects/data.json
Vendored
+20781
File diff suppressed because it is too large
Load Diff
+21
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"title":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/h1",
|
||||
"cookies":"//*[@id='c-s-bn']",
|
||||
"extend_elements":"html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]//ins[@class='jstree-icon']",
|
||||
"description":"//*[@id='projekttext']",
|
||||
"primary_metadata_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/div[",
|
||||
"primary_metadata_2":"]",
|
||||
"metadata_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[3]/div[1]/div[",
|
||||
"metadata_2":"]",
|
||||
"person_link":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/div[1]/span[2]/a",
|
||||
"person_name":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/h1",
|
||||
"person_address":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[1]/p[1]/span[2]",
|
||||
"person_metadata":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[4]/div[1]/ul",
|
||||
"current_projects":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[3]/div[1]/h2",
|
||||
"current_projects_ul":"//div[@id='laufendeProjekte']//ul[contains(@class,'projectList')]",
|
||||
"project_results_button":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/ul/li[2]/a",
|
||||
"project_results_summary":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[3]/div[1]/p",
|
||||
"project_results_header":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[3]/div[1]/h2",
|
||||
"project_results_publications_ul":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[3]/div[2]/div[3]/div[1]/ul"
|
||||
|
||||
}
|
||||
+395
@@ -0,0 +1,395 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException, WebDriverException, TimeoutException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
|
||||
DEFAULT_WAIT_TIMEOUT = 15
|
||||
SHORT_WAIT_TIMEOUT = 10
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Utilities
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def normalize_key(raw_key):
|
||||
return raw_key.lower().replace("-", " ").replace(" ", "_")
|
||||
|
||||
def get_id(url):
|
||||
return url.split("/")[-1]
|
||||
|
||||
def parse_name(raw: str) -> str:
|
||||
name = raw.replace("\n", " ").strip()
|
||||
parts = name.split(", ", 1)
|
||||
return f"{parts[1]} {parts[0]}" if len(parts) == 2 else name
|
||||
|
||||
def does_elem_exist(driver, xpath):
|
||||
try:
|
||||
driver.find_element(By.XPATH, xpath)
|
||||
return True
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
|
||||
def safe_get_text_from_xpath(driver, xpath, timeout=SHORT_WAIT_TIMEOUT):
|
||||
try:
|
||||
element = WebDriverWait(driver, timeout).until(
|
||||
EC.presence_of_element_located((By.XPATH, xpath))
|
||||
)
|
||||
text = element.text.replace("\n", " ").strip()
|
||||
return text if text else ""
|
||||
except (TimeoutException, NoSuchElementException, WebDriverException):
|
||||
return ""
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Log helpers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def load_log(log_name="dfg_data_crawler_log.json"):
|
||||
if os.path.exists(log_name):
|
||||
with open(log_name, 'r') as f:
|
||||
return json.load(f)
|
||||
log = {"done": [], "failed": []}
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
return log
|
||||
|
||||
def save_log(log, log_name="dfg_data_crawler_log.json"):
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Page setup
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def load_page(driver, url, config):
|
||||
"""Navigate to URL and wait for title element. Retries once on timeout."""
|
||||
driver.get(url)
|
||||
try:
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["title"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print(f"Timeout on {url}, retrying...")
|
||||
driver.get(url)
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["title"]))
|
||||
)
|
||||
|
||||
def accept_cookies(driver, config):
|
||||
try:
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.element_to_be_clickable((By.XPATH, config["cookies"]))
|
||||
).click()
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
def expand_all_elements(driver, config):
|
||||
for e in driver.find_elements(By.XPATH, config["extend_elements"]):
|
||||
try:
|
||||
e.click()
|
||||
except:
|
||||
pass
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Metadata block scraper (shared pattern)
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_metadata_block(driver, data, data_names, path_prefix_1, path_prefix_2, start=1, label_prefix=""):
|
||||
"""
|
||||
Iterates over span-based metadata rows (label in span[1], value in span[2]).
|
||||
Optionally prefixes keys with label_prefix (e.g. 'project_results_').
|
||||
Stores anchor data as nested list of objects: [{"text": ..., "id": ..., "url": ...}]
|
||||
"""
|
||||
counter = start
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
while does_elem_exist(driver, elem_path):
|
||||
try:
|
||||
raw_label = safe_get_text_from_xpath(driver, elem_path + "/span[1]")
|
||||
label = label_prefix + normalize_key(raw_label)
|
||||
|
||||
if label:
|
||||
if label not in data_names:
|
||||
data_names.append(label)
|
||||
|
||||
anchors = driver.find_elements(By.XPATH, elem_path + "/span[2]/a")
|
||||
if anchors:
|
||||
data[label] = [
|
||||
{
|
||||
"text": a.text,
|
||||
"id": get_id(a.get_attribute("href")),
|
||||
"url": a.get_attribute("href"),
|
||||
}
|
||||
for a in anchors
|
||||
]
|
||||
else:
|
||||
data[label] = safe_get_text_from_xpath(driver, elem_path + "/span[2]")
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
counter += 1
|
||||
elem_path = path_prefix_1 + str(counter) + path_prefix_2
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Section scrapers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_basic_info(driver, data, config):
|
||||
data["title"] = safe_get_text_from_xpath(driver, config["title"])
|
||||
data["description"] = safe_get_text_from_xpath(driver, config["description"])
|
||||
|
||||
def scrape_funding_years(data):
|
||||
"""Parse funding_start / funding_end from the 'förderung' field if present."""
|
||||
förderung = data.get("förderung", "")
|
||||
if not förderung:
|
||||
return
|
||||
if "seit" in förderung:
|
||||
data["funding_start"] = int(förderung[-4:])
|
||||
data["funding_end"] = 2999
|
||||
elif "in" in förderung:
|
||||
data["funding_start"] = int(förderung[-4:])
|
||||
data["funding_end"] = int(förderung[-4:])
|
||||
elif "von" in förderung:
|
||||
data["funding_start"] = int(förderung[-13:-9])
|
||||
data["funding_end"] = int(förderung[-4:])
|
||||
|
||||
def scrape_project_results(driver, data, data_names, config):
|
||||
if not does_elem_exist(driver, config["project_results_button"]):
|
||||
return
|
||||
print("Fetching project results")
|
||||
try:
|
||||
driver.find_element(By.XPATH, config["project_results_button"]).click()
|
||||
scrape_metadata_block(
|
||||
driver, data, data_names,
|
||||
config["metadata_1"], config["metadata_2"],
|
||||
start=1,
|
||||
label_prefix="project_results_"
|
||||
)
|
||||
if does_elem_exist(driver, config["project_results_summary"]):
|
||||
data["project_results_summary"] = safe_get_text_from_xpath(
|
||||
driver, config["project_results_summary"]
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"project results error: {e}")
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Running projects & publications
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def handle_current_projects(driver, xpath, data):
|
||||
print("Handling running projects")
|
||||
try:
|
||||
items = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.XPATH, xpath + "/li"))
|
||||
)
|
||||
except TimeoutException:
|
||||
print("Running projects not found")
|
||||
return data
|
||||
|
||||
data["current_projects"] = []
|
||||
for li in items:
|
||||
try:
|
||||
title_el = li.find_element(By.XPATH, "./a[1]")
|
||||
project = {
|
||||
"title": title_el.get_attribute("textContent").replace("\n", " ").strip(),
|
||||
"url": title_el.get_attribute("href"),
|
||||
"id": get_id(title_el.get_attribute("href")),
|
||||
"teilprojektleiter": [
|
||||
{
|
||||
"name": parse_name(p.get_attribute("textContent")),
|
||||
"url": p.get_attribute("href"),
|
||||
"id": get_id(p.get_attribute("href")),
|
||||
}
|
||||
for p in li.find_elements(By.XPATH, ".//a[contains(@href,'/gepris/person/')]")
|
||||
],
|
||||
"meta_raw": li.get_attribute("textContent").replace("\n", " ").strip()
|
||||
}
|
||||
data["current_projects"].append(project)
|
||||
except Exception as e:
|
||||
print(f"Running project parse error: {e}")
|
||||
return data
|
||||
|
||||
def handle_project_results_publications(driver, xpath, data):
|
||||
print("Handling publications")
|
||||
try:
|
||||
items = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.XPATH, xpath + "/li"))
|
||||
)
|
||||
except TimeoutException:
|
||||
print("Publications not found")
|
||||
return data
|
||||
|
||||
data["project_results_publications"] = []
|
||||
for li in items:
|
||||
try:
|
||||
headline = li.find_element(By.XPATH, ".//span[contains(@class,'publications-headline')]")
|
||||
title = headline.text.replace("\n", " ").strip()
|
||||
try:
|
||||
url = headline.find_element(By.XPATH, ".//a").get_attribute("href")
|
||||
except NoSuchElementException:
|
||||
url = None
|
||||
|
||||
full_text = li.get_attribute("textContent").strip()
|
||||
data["project_results_publications"].append({
|
||||
"title": title,
|
||||
"url": url,
|
||||
"authors_raw": full_text.replace(title, "", 1).strip(),
|
||||
"meta_raw": full_text
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"Publication parse error: {e}")
|
||||
return data
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Main pipeline
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def scrape_project(driver, url, config, data_names):
|
||||
"""Scrape a single project page. Returns data dict or None on failure."""
|
||||
data = {
|
||||
"url": url,
|
||||
"id": url[url.rfind("/") + 1:]
|
||||
}
|
||||
|
||||
# 1. Load page
|
||||
load_page(driver, url, config)
|
||||
|
||||
# 2. Accept cookies (only fires once, then silently skipped)
|
||||
accept_cookies(driver, config)
|
||||
|
||||
# 3. Expand collapsed sections
|
||||
expand_all_elements(driver, config)
|
||||
|
||||
# 4. Title + description
|
||||
scrape_basic_info(driver, data, config)
|
||||
|
||||
# 5. Primary metadata block (upper details)
|
||||
print("Fetching primary metadata")
|
||||
scrape_metadata_block(
|
||||
driver, data, data_names,
|
||||
config["primary_metadata_1"], config["primary_metadata_2"],
|
||||
start=1
|
||||
)
|
||||
|
||||
# 6. Running sub-projects (if present)
|
||||
if does_elem_exist(driver, config["current_projects"]):
|
||||
data = handle_current_projects(driver, config["current_projects_ul"], data)
|
||||
|
||||
# 7. Secondary metadata block (lower details)
|
||||
print("Fetching secondary metadata")
|
||||
scrape_metadata_block(
|
||||
driver, data, data_names,
|
||||
config["metadata_1"], config["metadata_2"],
|
||||
start=2
|
||||
)
|
||||
|
||||
# 8. Project results section (click button → scrape)
|
||||
scrape_project_results(driver, data, data_names, config)
|
||||
|
||||
# 9. Publications list
|
||||
if does_elem_exist(driver, config["project_results_publications_ul"]):
|
||||
data = handle_project_results_publications(
|
||||
driver, config["project_results_publications_ul"], data
|
||||
)
|
||||
|
||||
# 10. Derive funding years from 'förderung' field
|
||||
scrape_funding_years(data)
|
||||
|
||||
# 11. Click through to person page and scrape details
|
||||
#scrape_person_details(driver=driver, data=data,data_names=data_names, config=config)
|
||||
|
||||
return data
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
def project_level(driver, project_links, config):
|
||||
log = load_log()
|
||||
|
||||
data_names = [
|
||||
"id", "url", "title", "description", "funding_start", "funding_end",
|
||||
"person_creator_url", "person_creator_id", "person_creator_name",
|
||||
"person_creator_address"
|
||||
]
|
||||
|
||||
# Load existing data if present
|
||||
if os.path.exists("data.json"):
|
||||
with open("data.json", "r", encoding="utf-8") as f:
|
||||
data_list = json.load(f)
|
||||
else:
|
||||
data_list = []
|
||||
|
||||
new_entries = 0
|
||||
|
||||
for i, url in enumerate(project_links):
|
||||
print(f"[{i+1}/{len(project_links)}] {url}")
|
||||
|
||||
if url in log["done"]:
|
||||
print(" Already crawled, skipping.")
|
||||
continue
|
||||
|
||||
try:
|
||||
data = scrape_project(driver, url, config, data_names)
|
||||
|
||||
data_list.append(data)
|
||||
log["done"].append(url)
|
||||
new_entries += 1
|
||||
|
||||
# Save every 10 successful entries
|
||||
if new_entries % 10 == 0:
|
||||
with open("data.json", "w", encoding="utf-8") as f:
|
||||
json.dump(data_list, f, ensure_ascii=False, indent=2)
|
||||
|
||||
save_log(log)
|
||||
print(f" Saved progress ({new_entries} new entries).")
|
||||
|
||||
except Exception as e:
|
||||
print(f" Failed: {e}")
|
||||
log["failed"].append(url)
|
||||
save_log(log)
|
||||
|
||||
# Final save
|
||||
with open("data.json", "w", encoding="utf-8") as f:
|
||||
json.dump(data_list, f, ensure_ascii=False, indent=2)
|
||||
|
||||
save_log(log)
|
||||
|
||||
print(f"Finished. Total records: {len(data_list)}")
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Entry point
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def read_config(path):
|
||||
with open(path, 'r') as f:
|
||||
return json.load(f)
|
||||
|
||||
def readInLinks():
|
||||
with open("links.json", "r", encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
#check_elastic_online()
|
||||
|
||||
project_links = readInLinks()[-50:]
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
driver = webdriver.Chrome(options=options)
|
||||
|
||||
print(f"Number of projects: {len(project_links)}")
|
||||
config = read_config("data_config.json")
|
||||
project_level(driver, project_links, config)
|
||||
|
||||
driver.close()
|
||||
print("Finished")
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"done": ["https://gepris.dfg.de/gepris/projekt/422213477", "https://gepris.dfg.de/gepris/projekt/422744262", "https://gepris.dfg.de/gepris/projekt/424638267", "https://gepris.dfg.de/gepris/projekt/424778381", "https://gepris.dfg.de/gepris/projekt/424957847", "https://gepris.dfg.de/gepris/projekt/426335750", "https://gepris.dfg.de/gepris/projekt/428312742", "https://gepris.dfg.de/gepris/projekt/429280966", "https://gepris.dfg.de/gepris/projekt/429529648", "https://gepris.dfg.de/gepris/projekt/438445824", "https://gepris.dfg.de/gepris/projekt/439669440", "https://gepris.dfg.de/gepris/projekt/444632635", "https://gepris.dfg.de/gepris/projekt/444845124", "https://gepris.dfg.de/gepris/projekt/449437943", "https://gepris.dfg.de/gepris/projekt/450149205", "https://gepris.dfg.de/gepris/projekt/452881907", "https://gepris.dfg.de/gepris/projekt/453596084", "https://gepris.dfg.de/gepris/projekt/456082119", "https://gepris.dfg.de/gepris/projekt/470903074", "https://gepris.dfg.de/gepris/projekt/471011418", "https://gepris.dfg.de/gepris/projekt/490846870", "https://gepris.dfg.de/gepris/projekt/491090170", "https://gepris.dfg.de/gepris/projekt/491392403", "https://gepris.dfg.de/gepris/projekt/491676693", "https://gepris.dfg.de/gepris/projekt/492547816", "https://gepris.dfg.de/gepris/projekt/492661287", "https://gepris.dfg.de/gepris/projekt/498601949", "https://gepris.dfg.de/gepris/projekt/501752319", "https://gepris.dfg.de/gepris/projekt/509149993", "https://gepris.dfg.de/gepris/projekt/511263698", "https://gepris.dfg.de/gepris/projekt/512007073", "https://gepris.dfg.de/gepris/projekt/514483642", "https://gepris.dfg.de/gepris/projekt/514664767", "https://gepris.dfg.de/gepris/projekt/514894665", "https://gepris.dfg.de/gepris/projekt/516748464", "https://gepris.dfg.de/gepris/projekt/520388526", "https://gepris.dfg.de/gepris/projekt/521256690", "https://gepris.dfg.de/gepris/projekt/521379614", "https://gepris.dfg.de/gepris/projekt/525069572", "https://gepris.dfg.de/gepris/projekt/528378584", "https://gepris.dfg.de/gepris/projekt/531327426", "https://gepris.dfg.de/gepris/projekt/531801029", "https://gepris.dfg.de/gepris/projekt/535081457", "https://gepris.dfg.de/gepris/projekt/540805631", "https://gepris.dfg.de/gepris/projekt/541063275", "https://gepris.dfg.de/gepris/projekt/542251251", "https://gepris.dfg.de/gepris/projekt/542264307", "https://gepris.dfg.de/gepris/projekt/543604419", "https://gepris.dfg.de/gepris/projekt/547068789", "https://gepris.dfg.de/gepris/projekt/559567011"], "failed": []}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.common.exceptions import WebDriverException
|
||||
from selenium.common.exceptions import TimeoutException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from random import randint
|
||||
import time
|
||||
import sys
|
||||
from elasticsearch import Elasticsearch
|
||||
import os
|
||||
import json
|
||||
|
||||
DEFAULT_WAIT_TIMEOUT = 10
|
||||
SHORT_WAIT_TIMEOUT = 5
|
||||
|
||||
def does_elem_exist(driver, xpath):
|
||||
try:
|
||||
driver.find_element(By.XPATH, xpath)
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
return True
|
||||
|
||||
def read_config(path):
|
||||
with open(path, 'r') as jsonfile:
|
||||
config = json.load(jsonfile)
|
||||
return config
|
||||
|
||||
|
||||
def getLinks(driver,config):
|
||||
print("Starting first level.")
|
||||
project_links = []
|
||||
|
||||
log = {}
|
||||
log_name = "dfg_links_crawler_log.json"
|
||||
if os.path.exists(log_name):
|
||||
# if json exists -> read in file
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
else:
|
||||
# if json doesn't exist -> #1 create json -> #2 write in initial structure -> #3 read it in
|
||||
# 1
|
||||
open(log_name, "x")
|
||||
# 2
|
||||
initial_dict = {"done": []}
|
||||
with open(log_name, "w") as jsonfile:
|
||||
jsonfile.write(json.dumps(initial_dict))
|
||||
# 3
|
||||
with open(log_name, 'r') as jsonfile:
|
||||
log = json.load(jsonfile)
|
||||
|
||||
index_counter = 0
|
||||
dfg_link_all_1 = config["start_url_1"]
|
||||
dfg_link_all_2 = config["start_url_2"]
|
||||
|
||||
while True:
|
||||
print(" - " + str(index_counter))
|
||||
if index_counter in log["done"]:
|
||||
print("- - Already crawled!")
|
||||
index_counter = index_counter + 50
|
||||
continue
|
||||
|
||||
dfg_link_all = dfg_link_all_1 + str(index_counter) + dfg_link_all_2
|
||||
|
||||
driver.get(dfg_link_all)
|
||||
|
||||
# Wait for the results header to be present
|
||||
try:
|
||||
WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["results_header"]))
|
||||
)
|
||||
except TimeoutException:
|
||||
print(f"Timeout waiting for results header on {dfg_link_all}. Continuing to next checks.")
|
||||
|
||||
# cookies
|
||||
try:
|
||||
WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.element_to_be_clickable((By.XPATH, config["cookies"]))
|
||||
).click()
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
# check if side exists, if not -> break loop (all links found)
|
||||
try:
|
||||
no_results_element = WebDriverWait(driver, SHORT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_element_located((By.XPATH, config["no_results"]))
|
||||
)
|
||||
text = no_results_element.text
|
||||
if text == "Ihre Suche ergab leider keine Treffer.":
|
||||
break
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
pass
|
||||
|
||||
# get project_links
|
||||
# Construct a common XPath for all project links based on the config parts
|
||||
common_links_xpath = config["link_1"] + "*" + config["link_2"]
|
||||
|
||||
try:
|
||||
# Wait for all project links to be present and retrieve them as a list of WebElements
|
||||
elements = WebDriverWait(driver, DEFAULT_WAIT_TIMEOUT).until(
|
||||
EC.presence_of_all_elements_located((By.XPATH, common_links_xpath))
|
||||
)
|
||||
|
||||
# Extract all href attributes from the retrieved elements at once
|
||||
links = [elem.get_attribute('href') for elem in elements if elem.get_attribute('href')]
|
||||
project_links.extend(links)
|
||||
print(f"Found {len(links)} project links on this page.")
|
||||
|
||||
except (TimeoutException, NoSuchElementException):
|
||||
print("No project links found on this page within the timeout or element not found.")
|
||||
|
||||
log["done"].append(index_counter)
|
||||
index_counter = index_counter + 50
|
||||
|
||||
# write new log
|
||||
with open(log_name, "w") as outfile:
|
||||
outfile.write(json.dumps(log))
|
||||
|
||||
write_links(project_links)
|
||||
|
||||
return project_links
|
||||
|
||||
def write_links(project_links):
|
||||
print(len(project_links))
|
||||
js = []
|
||||
if os.path.exists("links.json"):
|
||||
with open("links.json", 'r') as jsonfile:
|
||||
js = json.load(jsonfile)
|
||||
|
||||
for j in js:
|
||||
if j not in project_links:
|
||||
project_links.append(j)
|
||||
|
||||
with open("links.json", "w") as f:
|
||||
json.dump(project_links, f)
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
driver = webdriver.Chrome(options=options)
|
||||
config = read_config("links_config.json")
|
||||
project_links = getLinks(driver,config)
|
||||
|
||||
print("Number of projects: " + str(len(project_links)))
|
||||
|
||||
#write_links(project_links)
|
||||
|
||||
driver.close()
|
||||
|
||||
print("Finished")
|
||||
+1
File diff suppressed because one or more lines are too long
+205
@@ -0,0 +1,205 @@
|
||||
from elasticsearch import Elasticsearch, helpers
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
|
||||
from build_mapping import create_mapping
|
||||
es = Elasticsearch('https://inse.nes.uni-due.de:443/elastic', basic_auth=('elastic', 'RLldUaJgbGeoqd3KCX3p'), request_timeout=60, max_retries=5, retry_on_timeout=True)
|
||||
index_name = "dfg_projects_all_test"
|
||||
|
||||
def load_log(log_name="uploaded.json"):
|
||||
if os.path.exists(log_name):
|
||||
with open(log_name, 'r') as f:
|
||||
return json.load(f)
|
||||
log = {"done": [], "failed": []}
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
return log
|
||||
|
||||
def save_log(log, log_name="uploaded.json"):
|
||||
with open(log_name, "w") as f:
|
||||
json.dump(log, f)
|
||||
|
||||
# ─────────────────────────────────────────────
|
||||
# Elasticsearch helpers
|
||||
# ─────────────────────────────────────────────
|
||||
|
||||
def check_elastic_index(data_names, index_name, nested_field_names=None):
|
||||
if es.indices.exists(index=index_name):
|
||||
return
|
||||
|
||||
nested_field_names = nested_field_names or set()
|
||||
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"searchabilityAnalyzer": {
|
||||
"type": "custom", "tokenizer": "standard",
|
||||
"filter": ["lowercase", "asciifolding"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# def text_keyword(ignore_above=256):
|
||||
# return {
|
||||
# "type": "text",
|
||||
# "analyzer": "searchabilityAnalyzer",
|
||||
# "search_analyzer": "searchabilityAnalyzer",
|
||||
# "fields": {"keyword": {"type": "keyword", "ignore_above": ignore_above}}
|
||||
# }
|
||||
|
||||
# keyword = {"type": "keyword"}
|
||||
|
||||
# properties = {}
|
||||
# for name in data_names:
|
||||
# if name in ("funding_start", "funding_end"):
|
||||
# properties[name] = {"type": "integer"}
|
||||
|
||||
# elif name == "current_projects":
|
||||
# properties[name] = {
|
||||
# "type": "nested",
|
||||
# "properties": {
|
||||
# "project_id": keyword,
|
||||
# "project_url": keyword,
|
||||
# "project_title": text_keyword(ignore_above=1024),
|
||||
# "meta_raw": {"type": "text"},
|
||||
# "teilprojektleiter": {
|
||||
# "type": "nested",
|
||||
# "properties": {
|
||||
# "name": text_keyword(),
|
||||
# "id": keyword,
|
||||
# "url": keyword,
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
# }
|
||||
|
||||
# elif name == "project_results_publications":
|
||||
# properties[name] = {
|
||||
# "type": "nested",
|
||||
# "properties": {
|
||||
# "title": text_keyword(ignore_above=1024),
|
||||
# "url": keyword,
|
||||
# "authors_raw": {"type": "text"},
|
||||
# "meta_raw": {"type": "text"},
|
||||
# }
|
||||
# }
|
||||
|
||||
# elif name in nested_field_names:
|
||||
# properties[name] = {
|
||||
# "type": "nested",
|
||||
# "properties": {
|
||||
# "text": text_keyword(),
|
||||
# "id": keyword,
|
||||
# "url": keyword,
|
||||
# }
|
||||
# }
|
||||
|
||||
# else:
|
||||
# properties[name] = text_keyword()
|
||||
mappings = create_mapping("data.json")
|
||||
|
||||
es.indices.create(index=index_name, mappings=mappings, settings=settings)
|
||||
|
||||
|
||||
def check_elastic_online():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
|
||||
from elasticsearch import helpers
|
||||
import json
|
||||
|
||||
def upload_projects(data_list, index_name, log, chunk_size=500):
|
||||
"""Chunked bulk upload with safe logging."""
|
||||
|
||||
def chunkify(lst, size):
|
||||
for i in range(0, len(lst), size):
|
||||
yield lst[i:i + size]
|
||||
|
||||
total_success = 0
|
||||
|
||||
for chunk_idx, chunk in enumerate(chunkify(data_list, chunk_size)):
|
||||
actions = []
|
||||
|
||||
for doc in chunk:
|
||||
link = doc.get("link")
|
||||
id = doc.get("id")
|
||||
# skip already done
|
||||
if link in log["done"]:
|
||||
continue
|
||||
|
||||
actions.append({
|
||||
"_index": index_name,
|
||||
"_id": id,
|
||||
"_source": doc
|
||||
})
|
||||
|
||||
if not actions:
|
||||
continue
|
||||
|
||||
print(f"\nUploading chunk {chunk_idx + 1} ({len(actions)} docs)...")
|
||||
|
||||
try:
|
||||
success, errors = helpers.bulk(
|
||||
es,
|
||||
actions,
|
||||
raise_on_error=False,
|
||||
stats_only=False
|
||||
)
|
||||
|
||||
total_success += success
|
||||
|
||||
for action in actions:
|
||||
log["done"].append(action["_id"])
|
||||
|
||||
print(f"Chunk {chunk_idx + 1}: {success} indexed")
|
||||
|
||||
|
||||
if errors:
|
||||
print(f"Chunk {chunk_idx + 1}: some failures")
|
||||
for err in errors:
|
||||
try:
|
||||
failed_id = err["index"]["_id"]
|
||||
log["failed"].append(failed_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
print(f"Chunk {chunk_idx + 1} failed completely: {e}")
|
||||
for action in actions:
|
||||
log["failed"].append(action["_id"])
|
||||
|
||||
save_log(log)
|
||||
|
||||
print(f"\nDONE. Total indexed: {total_success}")
|
||||
if __name__ == "__main__":
|
||||
|
||||
check_elastic_online()
|
||||
|
||||
data_file = "data.json"
|
||||
if not os.path.exists(data_file):
|
||||
print(f"Error: {data_file} not found in current directory.")
|
||||
sys.exit(1)
|
||||
|
||||
with open(data_file, "r", encoding="utf-8") as f:
|
||||
projects = json.load(f)
|
||||
|
||||
all_field_names = set()
|
||||
nested_field_names = set()
|
||||
|
||||
for item in projects:
|
||||
all_field_names.update(item.keys())
|
||||
for key, value in item.items():
|
||||
if (
|
||||
isinstance(value, list)
|
||||
and value
|
||||
and isinstance(value[0], dict)
|
||||
):
|
||||
nested_field_names.add(key)
|
||||
|
||||
check_elastic_index(list(all_field_names), index_name, nested_field_names)
|
||||
|
||||
log = load_log()
|
||||
|
||||
upload_projects(projects, index_name,log)
|
||||
+1
File diff suppressed because one or more lines are too long
+9
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"start_url_1":"https://gepris.dfg.de/gepris/OCTOPUS?beginOfFunding=&bewilligungsStatus=&bundesland=DEU%23&context=projekt&einrichtungsart=-1&fachgebiet=%23&findButton=historyCall&gefoerdertIn=&ggsHunderter=0&hitsPerPage=50&index=",
|
||||
"start_url_2":"&nurProjekteMitAB=false&oldGgsHunderter=0&oldfachgebiet=%23&orderBy=gz&pemu=%23&task=doKatalog&teilprojekte=true&zk_transferprojekt=false",
|
||||
"results_header":"/html/body/div[1]/div/div[3]/div[1]/div/div/h1",
|
||||
"no_results":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[2]/div/p",
|
||||
"cookies":"//*[@id='c-s-bn']",
|
||||
"link_1":"/html/body/div[1]/div/div[3]/div[1]/div/div/div[1]/div/div[2]/div[3]/div[",
|
||||
"link_2":"]/div[1]/h2/a"
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"done": ["422213477", "422744262", "424638267", "424778381", "424957847", "426335750", "428312742", "429280966", "429529648", "438445824", "439669440", "444632635", "444845124", "449437943", "450149205", "452881907", "453596084", "456082119", "470903074", "471011418", "490846870", "491090170", "491392403", "491676693", "492547816", "492661287", "498601949", "501752319", "509149993", "511263698", "512007073", "514483642", "514664767", "514894665", "516748464", "520388526", "521256690", "521379614", "525069572", "528378584", "531327426", "531801029", "535081457", "540805631", "541063275", "542251251", "542264307", "543604419", "547068789", "559567011"], "failed": []}
|
||||
Reference in New Issue
Block a user