5 Commits
46 changed files with 55320 additions and 48952 deletions
Binary file not shown.
Binary file not shown.
-87
View File
@@ -1,87 +0,0 @@
[BMBF]
allowed-domain = foerderportal.bund.de
container = //div[@class='detailAnsicht']
foerderkennzeichen = normalize-space(.//div[@class='detailAnsichtItem']/div[contains(text(),'Förderkennzeichen')]/parent::*/div[2]/text())
thema = normalize-space(.//div[@class='detailAnsichtItem']/div[contains(text(),'Thema')]/parent::*/div[2]/text())
verbund = normalize-space(.//div[@class='detailAnsichtItem']/div[contains(text(),'Verbund')]/parent::*/div[2]/form[@id='sucheVerbund']/a/text())
foerdersumme = normalize-space(.//div[@class='detailAnsichtItem']/div[contains(text(),'Fördersumme')]/parent::*/div[2]/text())
ressort = normalize-space(.//div[@class='detailAnsichtItem']/div[contains(text(),'Ressort')]/parent::*/div[2]/text())
projekttraeger = normalize-space(.//div[@class='detailAnsichtItem']/div[contains(text(),'Projektträger')]/parent::*/div[2]/text())
laufzeit = normalize-space(.//div[@class='detailAnsichtItem']/div[contains(text(),'Laufzeit')]/parent::*/div[2]/text())
leistungsplansystematik = normalize-space(.//div[@class='detailAnsichtItem']/div[contains(text(),'Leistungsplansystematik')]/parent::*/div[2]/text())
foerderart = normalize-space(.//div[@class='detailAnsichtItem']/ div[contains(text(),'Förderart')]/parent::*/div[2]/text())
foerderprofil = normalize-space(.//div[contains(text(),'Förderprofil')]/parent::*/div[2]/text())
zuwendungsempfaenger = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat des Zuwendungsempfängers']/child::div[1]
z_empf = normalize-space(./following-sibling::div[1]/text())
z_empf_ort = normalize-space(./following-sibling::div[3]/text())
z_empf_Bundesland_stadt = normalize-space(./following-sibling::div[5]/text())
Ausfuehrende_Stellen = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat der Ausführenden Stelle']/child::div[1]
a_stelle = normalize-space(./following-sibling::div[1]/text())
a_stelle_ort = normalize-space(./following-sibling::div[3]/text())
a_stelle_Bundesland_stadt = normalize-space(./following-sibling::div[5]/text())
[DFG]
allowed-domain = gepris.dfg.de
details_container = //div[@class='content_inside detailed']/div[@class='details']
title = normalize-space(.//h1[@class='facelift']/text())
antragsteller = .//div/span[@class='name' and contains(text(), ' Antragsteller')]/parent::*/span[@class='value']/descendant::a/text()
fachliche_Zuordnung = .//div[@class='firstUnderAntragsbeteiligte']/span[@class='value']/text()
foerderung = normalize-space(.//div/span[@class='value' and contains(text(), 'Förderung')]/text())
Projektkennung = normalize-space(.//div[@class='projektnummer']/span[@class='value']/text())
Website = .//div//span[@class='value']/a[@title='Webseite' and @class='extern']/@href
beschreibung_container = //div[@class='content_frame']/div[@id='projektbeschreibung']
project_text = normalize-space(.//div[@id='projekttext']/text())
DFG_Verfahren = normalize-space(.//div/span[contains(text(),' DFG-Verfahren')]//parent::*/span[2]/text())
geraetegruppe = normalize-space(.//div/span[contains(text(),' Gerätegruppe')]//parent::*/span[2]/text())
grossgereate = normalize-space(.//div/span[contains(text(),'Großgeräte')]//parent::*/span[2]/text())
antragstellende_Institution = normalize-space(.//div/span[contains(text(),'Antragstellende Institution')]//parent::*/span[2]/a/text())
leiter = normalize-space(.//div/span[contains(text(),'Leiter')]//parent::*/span[2]/a/text())
mitverantwortliche = .//div/span[contains(text(),'Mitverantwortliche')]//parent::*/span[2]/a[@class='intern']/text()
beteiligte_Person = .//div/span[contains(text(),' Beteiligte Person')]//parent::*/span[2]/descendant::a[@class='intern']/text()
teilprojekt_zu = .//div/span[contains(text(),'Teilprojekt zu')]//parent::*/span[2]/descendant::a[@class='intern']/text()
kooperationspartner = .//div/span[contains(text(),' Kooperationspartner')]//parent::*/span[2]/descendant::a[@class='intern']/text()
internationaler_Bezug = normalize-space(.//div/span[contains(text(),'Internationaler Bezug')]//parent::*/span[2]/text())
Sprecher = .//div/span[contains(text(),' Sprecher')]//parent::*/span[2]/descendant::a[@class='intern']/text()
beteiligte_Institution = .//div/span[contains(text(),' Beteiligte Institution')]//parent::*/span[2]/child::*/text()
beteiligte_Hochschule = .//div/span[contains(text(),' Beteiligte Hochschule')]//parent::*/span[2]/descendant::a/text()
mitantragstellende_Institution= normalize-space(.//div/span[contains(text(),' Mitantragstellende Institution')]//parent::*/span[2]/descendant::a/text())
beteiligte_Wissenschaftler = .//div/span[contains(text(),' beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler')]//parent::*/span[2]/descendant::a[@class='intern']/text()
IGK_Partnerinstitution = normalize-space(.//div/span[contains(text(),' IGK-Partnerinstitution')]//parent::*/span[2]/a[@class='intern']/text())
partnerorganisation = normalize-space(.//div/span[contains(text(),' Partnerorganisation')]//parent::*/span[2]/a[@class='intern']/text())
gastgeber = .//div/span[contains(text(),' Gastgeber')]//parent::*/span[2]/descendant::a[@class='intern']/text()
anwendungspartner = .//div/span[contains(text(),' Anwendungspartner')]//parent::*/span[2]/descendant::a[@class='intern']/text()
beteiligte_Fachrichtungen = normalize-space(.//div/span[contains(text(),'Beteiligte Fachrichtungen')]//parent::*/span[2]/text())
ehemalige_Antragsteller = .//div/span[contains(text(),' Ehemalige Antragsteller')]//parent::*/span[2]/descendant::a/text()
[EU]
title_loading_phase = //div[contains(@class, 'c-header-project__title-container')]/h1[contains(@class, 'c-header-project__title')]
title = //div[contains(@class, 'c-header-project__title-container')]/h1[contains(@class, 'c-header-project__title')]
content_container_loading_phase = //article
content_container = //article
objective = //h2[contains(text(), ' Objective ')]/parent::*/p[contains(@class, 'c-article__text')]
programme = //h3[contains(text(), 'Programme(s)')]/parent::*/ul/li/a
project_description = //h2[contains(text(), 'Project description')]//parent::*//p[contains(@class, 'c-project-description__text') or contains(@class, 'c-article__text')]
proposal = //h3[contains(text(), 'Call for proposal')]/parent::*/p/span
fields_of_science_list = //h3[contains(text(), 'Fields of science')]/parent::*/ul/li[@class='ng-star-inserted']/child::span[@class='ng-star-inserted']
fields_of_science = ./a
topics = //h3[contains(text(), 'Topic(s)')]/parent::*/ul/li/a
funding_scheme = //h3[contains(text(), 'Funding Scheme')]/parent::*/a
coordinator = //h3[contains(text(), 'Coordinator')]/parent::*//div[contains(@class, 'c-part-info__title')]
coordinator_address = //h3[contains(text(), 'Coordinator')]/parent::*//div[contains(text(), ' Address ')]/parent::*/div[contains(@class, 'c-part-info__content')]
coordinator_region = //h3[contains(text(), 'Coordinator')]/parent::*//div[contains(text(), 'Region')]/parent::*/div[contains(@class, 'c-part-info__content')]
coordinator_activity_type = //h3[contains(text(), 'Coordinator')]/parent::*//div[contains(text(), 'Activity type')]/parent::*/div[contains(@class, 'c-part-info__content')]
coordinator_net_EU_contribution = //h3[contains(text(), 'Coordinator')]/parent::*//div[contains(text(), 'Net EU contribution')]/parent::*/div[contains(@class, 'c-part-info__content')]
coordinator_other_fundings = //h3[contains(text(), 'Coordinator')]/parent::*//div[contains(text(), 'Other funding')]/parent::*/div[contains(@class, 'c-part-info__content')]
coordinator_link = //h3[contains(text(), 'Coordinator')]/parent::*//div[contains(text(), 'Links')]/parent::*//span/a
project_info_container_loading_phase = //app-project-info//div[@class='c-project-info__content']
project_info_container = //app-project-info//div[@class='c-project-info__content']
grant_agreement_ID = //div[contains(text(), 'Grant agreement ID')]
doi = //span[contains(text(), 'DOI')]/parent::*/a
project_acronym = //div[@class='c-project-info__acronym']
start_date = //span[contains(text(), 'Start date')]/parent::*
end_date = //span[contains(text(), 'End date')]/parent::*
funded_under = //span[contains(text(), 'Funded under')]/parent::*/ul/li
overal_budget = //span[contains(text(), 'Overall budget') or contains(text(), 'Total cost')]/parent::*
EU_contribution = //span[contains(text(), 'EU contribution')]/parent::*
-756
View File
@@ -1,756 +0,0 @@
########################################################################################################################################
import scrapy
from configparser import ConfigParser
import os
import codecs
import pandas as pd
class ProjectDataSpider(scrapy.Spider):
name = 'project-data'
config = ConfigParser()
with codecs.open(os.getcwd() + './Bachelorarbeit/data_config.ini', 'r', encoding='utf-8') as f :
config.read_file(f)
domains = config['DFG']['allowed-domain']
allowed_domains = [domains]
def __init__(self, start_urls=None):
super(ProjectDataSpider, self).__init__()
self.start_urls = start_urls.split(',') if start_urls else []
self.items = []
def start_requests(self):
for url in self.start_urls:
# print(url)
yield scrapy.Request(url, callback=self.parse)
def parse(self, response):
config_data = self.config['DFG']
title = ''
antragsteller = ''
fachliche_Zuordnung = ''
foerderung = ''
Projektkennung = ''
Website = ''
for Detail in response.xpath(config_data['details_container']):
try:
title = Detail.xpath(config_data['title']).get()
except:
pass
try:
antragsteller = Detail.xpath("normalize-space(" + config_data['antragsteller'] + ")").getall()#apply normalize here
except:
pass
try:
fachliche_Zuordnung = Detail.xpath(config_data['fachliche_Zuordnung']).getall()
except:
pass
try:
foerderung = Detail.xpath(config_data['foerderung']).get()
except:
pass
try:
Projektkennung = Detail.xpath(config_data['Projektkennung']).get()
except:
pass
try:
Website = Detail.xpath(config_data['Website']).get()
except:
pass
project_text = ''
DFG_Verfahren = ''
geraetegruppe = ''
grossgereate = ''
antragstellende_Institution = ''
leiter = ''
mitverantwortliche = ''
beteiligte_Person = ''
teilprojekt_zu = ''
kooperationspartner = ''
internationaler_Bezug = ''
Sprecher = ''
beteiligte_Institution = ''
beteiligte_Hochschule = ''
mitantragstellende_Institution = ''
beteiligte_Wissenschaftler = ''
IGK_Partnerinstitution = ''
partnerorganisation = ''
gastgeber = ''
anwendungspartner = ''
beteiligte_Fachrichtungen = ''
ehemalige_Antragsteller = ''
for Beschreibung in response.xpath(config_data['beschreibung_container']):
try:
project_text = Beschreibung.xpath(config_data['project_text']).get()
except:
pass
try:
DFG_Verfahren = Beschreibung.xpath(config_data['DFG_Verfahren']).get()
except:
pass
try:
antragstellende_Institution = Beschreibung.xpath(config_data['antragstellende_Institution']).get()
except:
pass
try:
geraetegruppe = Beschreibung.xpath(config_data['geraetegruppe']).get()
except:
pass
try:
grossgereate = Beschreibung.xpath(config_data['grossgereate']).get()
except:
pass
try:
leiter = Beschreibung.xpath(config_data['leiter']).get()
except:
pass
try:
mitverantwortliche = Beschreibung.xpath(config_data['mitverantwortliche']).getall()
except:
pass
try:
beteiligte_Person = Beschreibung.xpath(config_data['beteiligte_Person']).get()
except:
pass
try:
teilprojekt_zu = Beschreibung.xpath(config_data['teilprojekt_zu']).get()
except:
pass
try:
kooperationspartner = Beschreibung.xpath(config_data['kooperationspartner']).get()
except:
pass
try:
internationaler_Bezug = Beschreibung.xpath(config_data['internationaler_Bezug']).getall()
except:
pass
try:
Sprecher = Beschreibung.xpath(config_data['Sprecher']).getall()
except:
pass
try:
beteiligte_Institution = Beschreibung.xpath(config_data['beteiligte_Institution']).get()
except:
pass
try:
beteiligte_Hochschule = Beschreibung.xpath(config_data['beteiligte_Hochschule']).get()
except:
pass
try:
mitantragstellende_Institution = Beschreibung.xpath(config_data['mitantragstellende_Institution']).get()
except:
pass
try:
beteiligte_Wissenschaftler = Beschreibung.xpath(config_data['beteiligte_Wissenschaftler']).getall()
except:
pass
try:
IGK_Partnerinstitution = Beschreibung.xpath(config_data['IGK_Partnerinstitution']).get()
except:
pass
try:
partnerorganisation = Beschreibung.xpath(config_data['partnerorganisation']).get()
except:
pass
try:
gastgeber = Beschreibung.xpath(config_data['gastgeber']).getall()
except:
pass
try:
anwendungspartner = Beschreibung.xpath(config_data['anwendungspartner']).getall()
except:
pass
try:
beteiligte_Fachrichtungen = Beschreibung.xpath(config_data['beteiligte_Fachrichtungen']).getall()
except:
pass
try:
ehemalige_Antragsteller = Beschreibung.xpath(config_data['ehemalige_Antragsteller']).getall()
except:
pass
item = {
'Title': title,
'Antragsteller': antragsteller,
'Fachliche Zuordnung': fachliche_Zuordnung,
'Förderung': foerderung,
'Projektkennung' : Projektkennung,
'Website' : Website,
'Projecttext' : project_text,
'DFG Verfahren' : DFG_Verfahren,
'Gerätegruppe' : geraetegruppe,
'Grossgeräte' : grossgereate,
'Antragstellende Institution' : antragstellende_Institution,
'Leiter' : leiter,
'Mitverantwortliche' : mitverantwortliche,
'Beteiligte Personen' : beteiligte_Person,
'Teilprojekt zu' : teilprojekt_zu,
'Kooperationspartner' : kooperationspartner,
'Internationaler Bezug': internationaler_Bezug,
'Sprecher' : Sprecher,
'Beteiligte Institution' : beteiligte_Institution,
'Beteiligte Hochschule' : beteiligte_Hochschule,
'Mitantragstellende_Institution' : mitantragstellende_Institution,
'Beteiligte Wissenschaftler' : beteiligte_Wissenschaftler,
'IGK Partnerinstitution' : IGK_Partnerinstitution,
'Partnerorganisation' : partnerorganisation,
'Gastgeber' : gastgeber,
'Anwendungspartner': anwendungspartner,
'Beteiligte Fachrichtungen' : beteiligte_Fachrichtungen,
'Ehemalige Antragsteller': ehemalige_Antragsteller
}
self.items.append(item)
df = pd.DataFrame(self.items)
df.to_json('DFG_all_data.json', orient='records', force_ascii=False)
##########################################################################################################
import scrapy
from configparser import ConfigParser
import os
import codecs
import pandas as pd
class ProjectDataSpider(scrapy.Spider):
name = 'project-data'
config = ConfigParser()
with codecs.open(os.getcwd() + './Bachelorarbeit/data_config.ini', 'r', encoding='utf-8') as f :
config.read_file(f)
domains = config['DFG']['allowed-domain']
allowed_domains = [domains]
def __init__(self, start_urls=None):
super(ProjectDataSpider, self).__init__()
self.start_urls = start_urls.split(',') if start_urls else []
self.items = []
def start_requests(self):
for url in self.start_urls:
# print(url)
yield scrapy.Request(url, callback=self.parse)
def parse(self, response):
# ----------------------------------- BMBF Project ------------------------------ #
#config_data = self.config['BMBF']
# foerderkennzeichen = ''
# thema = ''
# verbund = ''
# foerdersumme = ''
# ressort = ''
# projekttraeger= ''
# laufzeit = ''
# leistungsplansystematik = ''
# foerderart = ''
# z_empf= ''
# z_empf_ort= ''
# z_empf_Bundesland_stadt = ''
# a_stelle = ''
# a_stelle_ort = ''
# a_stelle_Bundesland_stadt =''
# for Detail in response.xpath(config_data['container']):
# try:
# foerderkennzeichen = Detail.xpath(config_data['foerderkennzeichen']).get()
# except:
# pass
# try:
# thema = Detail.xpath(config_data['thema']).get()
# except:
# pass
# try:
# verbund = Detail.xpath(config_data['verbund']).get()
# except:
# verbund='Nein'
# try:
# foerdersumme = Detail.xpath(config_data['foerdersumme']).get()
# except:
# pass
# try:
# ressort = Detail.xpath(config_data['ressort']).get()
# except:
# pass
# try:
# projekttraeger = Detail.xpath(config_data['projekttraeger']).get()
# except:
# pass
# try:
# laufzeit = Detail.xpath(config_data['laufzeit']).get()
# except:
# pass
# try:
# leistungsplansystematik = Detail.xpath(config_data['leistungsplansystematik']).get()
# except:
# pass
# try:
# foerderart = Detail.xpath(config_data['foerderart']).get()
# except:
# pass
# try:
# foerderprofil = Detail.xpath(config_data['foerderprofil']).get()
# except:
# pass
# zuwendungsempfaenger = Detail.xpath(config_data['zuwendungsempfaenger'])
# for za in zuwendungsempfaenger:
# z_empf = za.xpath(config_data['z_empf']).get()
# z_empf_ort = za.xpath(config_data['z_empf_ort']).get()
# z_empf_Bundesland_stadt = za.xpath(config_data['z_empf_Bundesland_stadt']).get()
# Ausfuehrende_Stellen = Detail.xpath(config_data['Ausfuehrende_Stellen'])
# for stelle in Ausfuehrende_Stellen:
# a_stelle = stelle.xpath(config_data['a_stelle']).get()
# a_stelle_ort = stelle.xpath(config_data['a_stelle_ort']).get()
# a_stelle_Bundesland_stadt = stelle.xpath(config_data['a_stelle_Bundesland_stadt']).get()
# item = {
# 'Thema': thema,
# 'Förderkennzeichen': foerderkennzeichen,
# 'Verbund': verbund,
# 'Fördersumme' : foerdersumme,
# 'Ressort' : ressort,
# 'Projektträger': projekttraeger,
# 'Laufzeit': laufzeit,
# 'Leistungsplansystematik': leistungsplansystematik,
# 'Förderart': foerderart,
# 'Förderprofil': foerderprofil,
# 'Zuwendungsempfänger': [z_empf, z_empf_ort, z_empf_Bundesland_stadt],
# 'Ausführende Stellen': [a_stelle, a_stelle_ort, a_stelle_Bundesland_stadt]
# }
# self.items.append(item)
# df = pd.DataFrame(self.items)
# df.to_json('BMBF_all_data.json', orient='records', force_ascii=False)
# ------------------------------------------------------------------------------------------- #
# ------------------------------------- DFG Project ------------------------------------#
config_data = self.config['DFG']
title = ''
antragsteller = ''
fachliche_Zuordnung = ''
foerderung = ''
Projektkennung = ''
Website = ''
for Detail in response.xpath(config_data['details_container']):
try:
title = Detail.xpath(config_data['title']).get()
except:
pass
try:
antragsteller = Detail.xpath("normalize-space(" + config_data['antragsteller'] + ")").getall()#apply normalize here
except:
pass
try:
fachliche_Zuordnung = Detail.xpath(config_data['fachliche_Zuordnung']).getall()
except:
pass
try:
foerderung = Detail.xpath(config_data['foerderung']).get()
except:
pass
try:
Projektkennung = Detail.xpath(config_data['Projektkennung']).get()
except:
pass
try:
Website = Detail.xpath(config_data['Website']).get()
except:
pass
project_text = ''
DFG_Verfahren = ''
geraetegruppe = ''
grossgereate = ''
antragstellende_Institution = ''
leiter = ''
mitverantwortliche = ''
beteiligte_Person = ''
teilprojekt_zu = ''
kooperationspartner = ''
internationaler_Bezug = ''
Sprecher = ''
beteiligte_Institution = ''
beteiligte_Hochschule = ''
mitantragstellende_Institution = ''
beteiligte_Wissenschaftler = ''
IGK_Partnerinstitution = ''
partnerorganisation = ''
gastgeber = ''
anwendungspartner = ''
beteiligte_Fachrichtungen = ''
ehemalige_Antragsteller = ''
for Beschreibung in response.xpath(config_data['beschreibung_container']):
try:
project_text = Beschreibung.xpath(config_data['project_text']).get()
except:
pass
try:
DFG_Verfahren = Beschreibung.xpath(config_data['DFG_Verfahren']).get()
except:
pass
try:
antragstellende_Institution = Beschreibung.xpath(config_data['antragstellende_Institution']).get()
except:
pass
try:
geraetegruppe = Beschreibung.xpath(config_data['geraetegruppe']).get()
except:
pass
try:
grossgereate = Beschreibung.xpath(config_data['grossgereate']).get()
except:
pass
try:
leiter = Beschreibung.xpath(config_data['leiter']).get()
except:
pass
try:
mitverantwortliche = Beschreibung.xpath(config_data['mitverantwortliche']).getall()
except:
pass
try:
beteiligte_Person = Beschreibung.xpath(config_data['beteiligte_Person']).get()
except:
pass
try:
teilprojekt_zu = Beschreibung.xpath(config_data['teilprojekt_zu']).get()
except:
pass
try:
kooperationspartner = Beschreibung.xpath(config_data['kooperationspartner']).get()
except:
pass
try:
internationaler_Bezug = Beschreibung.xpath(config_data['internationaler_Bezug']).getall()
except:
pass
try:
Sprecher = Beschreibung.xpath(config_data['Sprecher']).getall()
except:
pass
try:
beteiligte_Institution = Beschreibung.xpath(config_data['beteiligte_Institution']).get()
except:
pass
try:
beteiligte_Hochschule = Beschreibung.xpath(config_data['beteiligte_Hochschule']).get()
except:
pass
try:
mitantragstellende_Institution = Beschreibung.xpath(config_data['mitantragstellende_Institution']).get()
except:
pass
try:
beteiligte_Wissenschaftler = Beschreibung.xpath(config_data['beteiligte_Wissenschaftler']).getall()
except:
pass
try:
IGK_Partnerinstitution = Beschreibung.xpath(config_data['IGK_Partnerinstitution']).get()
except:
pass
try:
partnerorganisation = Beschreibung.xpath(config_data['partnerorganisation']).get()
except:
pass
try:
gastgeber = Beschreibung.xpath(config_data['gastgeber']).getall()
except:
pass
try:
anwendungspartner = Beschreibung.xpath(config_data['anwendungspartner']).getall()
except:
pass
try:
beteiligte_Fachrichtungen = Beschreibung.xpath(config_data['beteiligte_Fachrichtungen']).getall()
except:
pass
try:
ehemalige_Antragsteller = Beschreibung.xpath(config_data['ehemalige_Antragsteller']).getall()
except:
pass
item = {
'Title': title,
'Antragsteller': antragsteller,
'Fachliche Zuordnung': fachliche_Zuordnung,
'Förderung': foerderung,
'Projektkennung' : Projektkennung,
'Website' : Website,
'Projecttext' : project_text,
'DFG Verfahren' : DFG_Verfahren,
'Gerätegruppe' : geraetegruppe,
'Grossgeräte' : grossgereate,
'Antragstellende Institution' : antragstellende_Institution,
'Leiter' : leiter,
'Mitverantwortliche' : mitverantwortliche,
'Beteiligte Personen' : beteiligte_Person,
'Teilprojekt zu' : teilprojekt_zu,
'Kooperationspartner' : kooperationspartner,
'Internationaler Bezug': internationaler_Bezug,
'Sprecher' : Sprecher,
'Beteiligte Institution' : beteiligte_Institution,
'Beteiligte Hochschule' : beteiligte_Hochschule,
'Mitantragstellende_Institution' : mitantragstellende_Institution,
'Beteiligte Wissenschaftler' : beteiligte_Wissenschaftler,
'IGK Partnerinstitution' : IGK_Partnerinstitution,
'Partnerorganisation' : partnerorganisation,
'Gastgeber' : gastgeber,
'Anwendungspartner': anwendungspartner,
'Beteiligte Fachrichtungen' : beteiligte_Fachrichtungen,
'Ehemalige Antragsteller': ehemalige_Antragsteller
}
self.items.append(item)
df = pd.DataFrame(self.items)
df.to_json('DFG_all_data.json', orient='records', force_ascii=False)
########################################################################################
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from configparser import ConfigParser
import codecs
import os
import pandas as pd
class ScrapeWithSelenium:
def __init__(self, urls):
# self.options = webdriver.ChromeOptions()
# self.options.add_argument('--headless')
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
self.driver.maximize_window()
self.urls = urls
self.config = ConfigParser()
self.run()
def scrape(self, url):
self.driver.get(url)
with codecs.open(os.getcwd() + './Bachelorarbeit/EU_xpath_config.ini', 'r', encoding='utf-8') as f :
self.config.read_file(f)
try:
config_data = self.config['EU']
try:
Title_loading_phase = WebDriverWait(self.driver,10).until(EC.presence_of_element_located((
By.XPATH, config_data['title_loading_phase']
)))
title = self.driver.find_element(By.XPATH, config_data['title']).text.strip()
except:
pass
programme=''
project_description = ''
objective =''
proposal = ''
topics = ''
funding_scheme = ''
coordinator=''
coordinator_address =''
coordinator_link= ''
fields_of_science = []
coordinator_region = ''
coordinator_activity_type=''
coordinator_net_EU_contribution=''
coordinator_other_fundings=''
Content_container_loading_phase = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((
By.XPATH, config_data['content_container_loading_phase'])))
content_container = self.driver.find_element(By.XPATH, config_data['content_container'])
try:
programme = content_container.find_element(By.XPATH, config_data['programme']).text.strip()
except:
pass
try:
objective = content_container.find_element(By.XPATH, config_data['objective']).text.strip()
except:
pass
try:
project_description = content_container.find_element(By.XPATH, config_data['project_description']).text.strip()
except:
pass
try:
proposal = content_container.find_element(By.XPATH, config_data['proposal']).text.strip()
except:
pass
try:
topics = content_container.find_element(By.XPATH, config_data['topics']).text.strip()
except:
pass
try:
funding_scheme = content_container.find_element(By.XPATH, config_data['funding_scheme']).text.strip()
except:
pass
try:
coordinator = content_container.find_element(By.XPATH, config_data['coordinator']).text.strip()
except:
pass
try:
coordinator_address = content_container.find_element(By.XPATH, config_data['coordinator_address']).text.strip()
except:
pass
try:
coordinator_activity_type = content_container.find_element(By.XPATH, config_data['coordinator_activity_type']).text.strip()
except:
pass
try:
coordinator_region = content_container.find_element(By.XPATH, config_data['coordinator_region']).text.strip()
except:
pass
try:
coordinator_net_EU_contribution = content_container.find_element(By.XPATH, config_data['coordinator_net_EU_contribution']).text.strip()
except:
pass
try:
coordinator_other_fundings = content_container.find_element(By.XPATH, config_data['coordinator_other_fundings']).text.strip()
except:
pass
try:
coordinator_link = content_container.find_element(By.XPATH, config_data['coordinator_link']).get_attribute('href').strip() #define for loop
except:
pass
try:
for fields in content_container.find_elements(By.XPATH, config_data['fields_of_science_list']):
fields_of_science.append(fields.find_element(By.XPATH, config_data['fields_of_science']).text.strip())
except:
pass
# ------------------------------ ptoject info card ------------------------------- #
project_info_container_loading_phase = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((
By.XPATH, config_data['project_info_container_loading_phase'])))
project_info_container = self.driver.find_element(By.XPATH, config_data['project_info_container'])
project_acronym=''
grant_agreement_ID=''
doi=''
start_date=''
end_date=''
funded_under=''
EU_contribution=''
overal_budget=''
try:
project_acronym = project_info_container.find_element(By.XPATH, config_data['project_acronym']).text.strip()
except:
pass
try:
grant_agreement_ID = project_info_container.find_element(By.XPATH, config_data['grant_agreement_ID']).text.strip()
except:
pass
try:
doi = project_info_container.find_element(By.XPATH, config_data['doi']).get_attribute('href').strip()
except:
pass
try:
start_date = project_info_container.find_element(By.XPATH, config_data['start_date']).text.strip()
except:
pass
try:
end_date = project_info_container.find_element(By.XPATH, config_data['end_date']).text.strip()
except:
pass
try:
funded_under = project_info_container.find_element(By.XPATH, config_data['funded_under']).text.strip()
except:
pass
try:
overal_budget = project_info_container.find_element(By.XPATH, config_data['overal_budget']).text.strip()
except:
pass
try:
EU_contribution = project_info_container.find_element(By.XPATH, config_data['EU_contribution']).text.strip()
except:
pass
return{
'Title': title,
'Programme': programme,
'Objective' : objective,
'Project description' : project_description,
'Proposal': proposal,
'Topic(s)': topics,
'Funding scheme': funding_scheme,
'Coordinator':coordinator,
'Coordinator_address':coordinator_address,
'Coordinator_activity_type':coordinator_activity_type,
'Coordinator_net_EU_contribution':coordinator_net_EU_contribution,
'Coordinator_region': coordinator_region,
'Coordinator_other_fundings':coordinator_other_fundings,
'Coordinator_link':coordinator_link,
'Fields of science':fields_of_science,
'Grant agreement ID':grant_agreement_ID,
'DOI':doi,
'Project Acronym':project_acronym,
'Start date': start_date,
'End date': end_date,
'Funded under':funded_under,
'Overal budget':overal_budget,
'EU contribution':EU_contribution
}
except:
return None
def run(self):
results = []
for url in self.urls:
result = self.scrape(url)
if result:
results.append(result)
df = pd.DataFrame(results)
df.to_json(self.config['EU']['data_set'], orient='records', force_ascii=False)
def __del__(self):
self.driver.quit()
-36
View File
@@ -1,36 +0,0 @@
[BMBF]
start-url = https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=searchmask
loading-project-data = //table[@aria-label='Suchergebnis']/tbody/tr
projects-container = //table[@aria-label='Suchergebnis']
projects-list = //tbody/tr
project = .//td/a[@title= 'Detailansicht' and contains(@aria-label, 'Thema')]
next-btn = //form[@id='listnext']/a[@href='#']
search-box = //input[@id='suche_nameZeStSuche']
search-btn = //input[@id='suche_general_search']
[DFG]
start-url = https://gepris.dfg.de/gepris/OCTOPUS
loading-project-data = //div[@id='liste']//div[@class='eintrag_alternate' or @class='eintrag']
projects-container = //div[@id='liste']
projects-list = //div[@id='liste']/div[@class='eintrag_alternate' or @class=' eintrag']
project = .//div[@class='results']/h2/a
next-btn = //div[@id='listennavi']/div[@class='listennaviright']/a[@class='nextactive']
search-box = //input[@id='keywords_criterion']
search-btn = //form[@id='searchform']//button
cookies = //div[@id='c-inr']//div[@id='c-bns']/button[contains(text(), 'Statistische / Analyse-Cookies akzeptieren')]
[EU]
start-url = https://cordis.europa.eu/search?q=contenttype%%3D%%27project%%27%%20AND%%20(%%27UNIVERSITAET%%27%%20AND%%20%%27DUISBURG-ESSEN%%27)&p=1&num=50&srt=Relevance:decreasing
loading-project-data = //section[contains(@class, 'c-search__results')]//app-card-search[@class='ng-star-inserted']
projects-container = //section[contains(@class, 'c-search__results')]
projects-list = //app-card-search[@class='ng-star-inserted']
project = .//a[contains(@class, 'c-card-search__title')]
next-btn = //ul[@class='c-pagination__list c-pagination__list--last']/li/a[contains(@class, 'c-pagination__page-link') and contains(@aria-label, 'Goto next page')]
cookies = //app-cookies-consent//div[contains(@class, 'co-cookie-consent__button-container')]/button[contains(text(), 'I accept cookies.')]
; search-box = //input[@id='keywords_criterion']
; search-btn = //form[@id='searchform']//button
-103
View File
@@ -1,103 +0,0 @@
# ------------------------- Overview -------------------- #
'''
link_extractor.py uses a selenium ChromeDriverManager to locate
all the project links available on a particular website.
This project links will be stored in a json file using pandas DataFrame
The xpath implimentation is stored in links_config.ini.
'''
# ---------------------------------------------------------#
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from configparser import ConfigParser
import os
import time
import pandas as pd
options = webdriver.ChromeOptions()
options.add_argument('--disable-cookies')
# options.add_argument('--headless')
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
driver.delete_all_cookies()
config = ConfigParser()
config.read(os.getcwd() + './links_config.ini')
url = config['example']['start-url']
driver.get(url)
driver.maximize_window()
# ----------------------------- Coockies ---------------------------------- #
consent_btn= WebDriverWait(driver,10).until(EC.presence_of_element_located((
By.XPATH, config['example']['cookies']
)))
if consent_btn:
consent_btn.click()
# ----------------------------- locate search box -> type the search word -> click on search button ---------------------------------- #
search_input = driver.find_element(By.XPATH, config['example']['search-box'])
search_input.send_keys("Universität Duisburg-Essen")
time.sleep(0.1)
search_btn = driver.find_element(By.XPATH, config['example']['search-btn'])
search_btn.click()
# ----------------------------- Pagination ---------------------------------- #
links = []
isNextDisabeled = False
while not isNextDisabeled:
try:
links_config = config['example']
projects_loading_phase = WebDriverWait(driver,10).until(EC.presence_of_element_located((
By.XPATH, links_config['loading-project-data']
)))
container = driver.find_element(By.XPATH, links_config['projects-container'])
projects = container.find_elements(By.XPATH, links_config['projects-list'])
for project in projects:
links.append(project.find_element(By.XPATH, links_config['project']).get_attribute("href"))
# Saving data into a json file:
df_links = pd.DataFrame({'project_link':links})
df_links.to_json("project_links_example.json", orient='records')
try:
next_btn = WebDriverWait(driver, 10).until(EC.presence_of_element_located(
(By.XPATH, links_config['next-btn'])
))
if "disabled" in next_btn.get_attribute('class'):
isNextDisabeled = True
elif next_btn:
driver.find_element(By.XPATH, links_config['next-btn']).click()
else:
isNextDisabeled = True
except:
isNextDisabeled = True
except Exception as e:
print(e, "main error")
isNextDisabeled = True
driver.close()
-51
View File
@@ -1,51 +0,0 @@
This frame work is designed to retrieve data from different websites with different structure.
currently:
level #1 of abstraction is done by implementing a config file which stores all the xpath of different fields of
the 3 provided websitel inks
level #2 of abstraction is done by implementing a test conditional based on the website's type (js-based or not)
############################################################################################################################
# step 1
1. open projectlinks directory
2. edit the links_config.ini
3. open links_extractor.py -> url = config['example']['start-url'] (and other relevent fields)
4. once you entered the configured data, links_extractor file will extract the project links by handeling pagination and saves them in project_links_ProjectName.json
# step 2
1. to determine wheather we need scrapy or delenium to scrape data from project links,
I passed the first link stored in project_links_ProjectName.json to selenium_or_scrapy.py
2. this file goes through html markup and searches for <noscript> tag
3. if <noscript> exists -> all the stored links will be sent to selenium.py located inside selenium_script folder
4. else the links will be directed to a spider called project_data.py ->
(subprocess.call(['scrapy', 'crawl', 'project-data', '-a', 'start_urls=' + ','.join(start_urls)]))
# step 3
1. the configuration data of all 3 websites are stored in data_config.ini
2. this file includes all the related expath as key-value pairs
3. both project_data.py(used for not js-based websites) and selenium.py (used for js-based files) use
the configured data via a library called configparser
# step 4
in order to run either selenium or scrapy step 1 , 2 and 3 should be done first.
both of the scripts are activated through selenium_or_scrapy.py
################################################################################################################
# When to use Scrapy for data retrieval:
1.The website can be easily scraped using traditional HTTP requests and parsing the HTML or XML.
2.You want to scrape multiple websites or pages with the same structure and don't need to interact with the website.
3.You want to scrape a large amount of data efficiently and with parallelism.
4.You want to automate the scraping process and schedule it to run periodically.
# When to use Selenium for data retrieval:
1.The website is built using JavaScript or other client-side technologies that require interaction to generate content that needs to be scraped.
2.The website implements anti-scraping measures that cannot be easily bypassed by making requests from a script.
3.The website requires login or authentication to access the data you want to scrape.
4.You need to simulate user behavior such as scrolling or clicking to navigate the website and collect data.
File diff suppressed because one or more lines are too long
-98
View File
@@ -1,98 +0,0 @@
# -------------------------- Overview -------------------------- #
'''
In Scrapy_or_Selenium.py file we pass the first project link stored
In an already scraped project link file(Here: "project_links_BMBF.json", "project_links_EU.json" and "project_links_DFG.json").
In order to check if a website is JavaScript enabled or not, one should check if the website works as expected by disableing
JS with chrome inspection tools.
In order to make this test automatic, I examined the html markup to see if it contains <noscript></noscript> or not.
If yes (JS-based): all the project urls of that specific file will be sent to selenium.py located in selenium_script directory
If no (not JS-based) : all the project urls of that specific file will be sent to project_data.py located inside spiders directory.
'''
# --------------------------------------------------------------- #
import requests
import json
import subprocess
from selenium_script.selenium import ScrapeWithSelenium
with open('./Projectlinks/project_links_EU.json', 'r', encoding='utf-8') as f:
jsonlinks = json.load(f)
test_link = jsonlinks[0]['project_link']
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0'}
response = requests.get(url=test_link, headers=headers)
if '<noscript' in response.text:
print('The website is JavaScript-based')
urls = [link['project_link'] for link in jsonlinks]
scraper = ScrapeWithSelenium(urls)
scraper.run()
else:
print('The website is not JavaScript-based')
start_urls = [link['project_link'] for link in jsonlinks]
subprocess.call(['scrapy', 'crawl', 'project-data', '-a', 'start_urls=' + ','.join(start_urls)])
+476
View File
@@ -0,0 +1,476 @@
import scrapy
from configparser import ConfigParser
import os
import pandas as pd
import logging
class ProjectLinksSpider(scrapy.Spider):
name = 'links'
def __init__(self, website_name=None, start_urls=None, config_path=None, allowed_domains=None):
super(ProjectLinksSpider, self).__init__()
self.config = ConfigParser()
self.config_path = config_path
self.website_name = website_name
self.allowed_domains = allowed_domains.split(',') if allowed_domains else []
self.start_urls = start_urls
if config_path:
with open(os.getcwd() + config_path, 'r') as f:
self.config.read_file(f)
self.project_links = []
def start_requests(self):
xpath = dict(self.config.items(self.website_name))
for url in self.start_urls:
yield scrapy.Request(url=url, callback=self.parse, meta={'xpath': xpath}, dont_filter=True)
def parse(self, response):
xpath = response.meta.get('xpath', {})
# Extract links
for project in response.xpath(xpath['project-list']):
link = response.urljoin(project.xpath(xpath['project-link']).get())
yield{
'link': link
}
self.project_links.append(link)
# Handle pagination
next_page = response.xpath(xpath['next-btn'])
if next_page is not None:
next_url = response.urljoin(next_page.get())
if next_url != response.url:
self.logger.info(f"Following next page: {next_url}")
yield scrapy.Request(url=next_url, callback=self.parse, dont_filter=True, meta={'xpath':xpath})
else:
self.save_links()
def save_links(self):
df = pd.DataFrame(self.project_links, columns=['project_link'])
df.to_json(f'project_links_{self.website_name}.json', orient='records')
'''
import scrapy
from configparser import ConfigParser
import os
import pandas as pd
import logging
class ProjectLinksSpider(scrapy.Spider):
name = 'links'
def __init__(self, website_name='DFG', start_urls='https://gepris.dfg.de/gepris/OCTOPUS?context=projekt&findButton=historyCall&hitsPerPage=125&index=0&keywords_criterion=Universit%C3%A4t+Duisburg-Essen&nurProjekteMitAB=false&orderBy=relevance&task=doSearchSimple', config_path='./config/links_config.ini', allowed_domains='gepris.dfg.de'):
super(ProjectLinksSpider, self).__init__()
self.config = ConfigParser()
self.config_path = config_path
self.website_name = website_name
self.allowed_domains = allowed_domains.split(',') if allowed_domains else []
self.start_urls = start_urls.split(',') if start_urls else []
if config_path:
with open(os.getcwd() + config_path, 'r') as f:
self.config.read_file(f)
self.project_links = []
def start_requests(self):
xpath = dict(self.config.items(self.website_name))
print(xpath)
for url in self.start_urls:
yield scrapy.Request(url=url, callback=self.parse, meta={'xpath': xpath}, dont_filter=True)
def parse(self, response):
xpath = response.meta.get('xpath', {})
# Extract links
for project in response.xpath(xpath['project-list']):
link = response.urljoin(project.xpath(xpath['project-link']).get())
yield{
'link': link
}
self.project_links.append(link)
# Handle pagination
next_page = response.xpath(xpath['next-btn'])
if next_page is not None:
next_url = response.urljoin(next_page.get())
if next_url != response.url:
self.logger.info(f"Following next page: {next_url}")
yield scrapy.Request(url=next_url, callback=self.parse, dont_filter=True, meta={'xpath':xpath})
else:
self.save_links()
def save_links(self):
df = pd.DataFrame(self.project_links, columns=['project_link'])
df.to_json(f'project_links_{self.website_name}.json', orient='records')
'''
import requests
from scrapy.crawler import CrawlerProcess
import argparse
import json
import logging
from requests.exceptions import MissingSchema
from scrapyscript.spiders.project_links import ProjectLinksSpider
from seleniumscript.project_links import ProjectLinksSelenium
from seleniumscript.project_data import ProjectDataSelenium
from scrapyscript.spiders.project_data import ProjectDataSpider
def main(start_urls):
def is_dynamic():
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0'}
response = requests.get(url=start_urls, headers=headers)
if input('Do you have to fill out an HTML form to access the project links?(y/n): ').lower() == 'y' or input('Does the search criteria appear in the URL as a parameter?(y/n): ').lower() == 'n' :
print('Framework uses Selenium to scrape project calls')
return True
elif input('Does the website load the entire page at once without delay?(y/n): ').lower() == 'n':
if '<noscript' in response.text:
print('Framework uses Selenium to scrape project calls')
return True
else:
print('Framework uses Scrapy to scrape project calls')
return False
def scrape_data_dynamic(project_links, website_name):
logging.info('Scraping project data...')
body_wait_time = int(input("Enter the amount of time you want to wait for each page to load in seconds: "))
xpath_wait_time = int(input("Enter the amount of time you want to wait for each field to load in seconds: "))
config_xpath = input("Enter the path to your xpath configuration file: ")
ProjectDataSelenium(urls=project_links,
website_name=website_name,
body_wait_time=body_wait_time,
xpath_wait_time=xpath_wait_time,
config_xpath=config_xpath)
def scrape_links_dynamic(start_urls, website_name, config_path):
logging.info('Scraping project links...')
body_wait_time = int(input("Enter the amount of time you want to wait for each page to load in seconds: "))
xpath_wait_time = int(input("Enter the amount of time you want to wait for each field to load in seconds: "))
ProjectLinksSelenium(start_urls=start_urls,
website_name=website_name,
config_path=config_path,
body_wait_time=body_wait_time,
xpath_wait_time=xpath_wait_time)
links = access_stored_links(website_name)
start_urls = [link['project_link'] for link in links]
scrape_data_dynamic(start_urls,website_name)
def scrape_data_static(project_links, website_name, allowed_domains):
config_xpath = input("Enter the path to your xpath configuration file: ")
process = CrawlerProcess()
process.crawl(ProjectDataSpider,
start_urls=project_links,
config_xpath=config_xpath,
website_name=website_name,
allowed_domains=allowed_domains)
def scrape_links_static(start_urls,config_path, website_name, allowed_domains):
process = CrawlerProcess()
process.crawl(ProjectLinksSpider,
website_name=website_name,
start_urls=start_urls,
config_path=config_path,
allowed_domains=allowed_domains)
process.start()
links = access_stored_links(website_name)
start_urls = [link['project_link'] for link in links]
scrape_data_static(project_links=start_urls, website_name=website_name, allowed_domains=allowed_domains)
def access_stored_links(name):
try:
with open(f'./project_links_{name}.json', 'r', encoding='utf-8') as f:
jsonlinks = json.load(f)
return jsonlinks
except FileNotFoundError:
print('File not found')
if is_dynamic():
website_name = input("Enter website name: ")
config_path = input("Enter path to links_config.ini: ")
scrape_links_dynamic(start_urls, website_name, config_path)
else:
website_name = input("Enter website name: ")
config_path = input("Enter the path to links_config.ini: ")
allowed_domains = input("Enter allowed domains: ")
scrape_links_static(start_urls=start_urls, config_path=config_path, website_name=website_name, allowed_domains=allowed_domains)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--start-urls', type=str, help='The start URL of the website to scrape')
args = parser.parse_args()
try:
main(start_urls=args.start_urls)
except (MissingSchema):
logging.error('Please provide the start URL of the website to scrape as string. Example: python main.py --start-urls "https://www.example.com"')
# if input('Do you have to fill out an HTML form to access the project links?(y/n): ').lower() == 'y':
# print('The website is dynamic')
# return True
# # 2
# elif input('Does the search criteria appear in the URL as a parameter?(y/n): ').lower() == 'n':
# print('The website is dynamic')
# return True
# # 3
# elif input('Does the website load the entire page at once without delay?(y/n): ').lower() == 'n':
# print('The website is dynamic')
# return True
# else:
# print('The website is static')
# return False
'''import requests
from scrapy.crawler import CrawlerProcess
import argparse
from scrapy.spiders import CallbackSpider
import json
import logging
from requests.exceptions import MissingSchema
from scrapyscript.spiders.project_links import ProjectLinksSpider
from seleniumscript.project_links import ProjectLinksSelenium
from seleniumscript.project_data import ProjectDataSelenium
from scrapyscript.spiders.project_data import ProjectDataSpider
def main(start_urls):
def is_dynamic():
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0'}
response = requests.get(url=start_urls, headers=headers)
if input('Do you have to fill out an HTML form to access the project links?(y/n): ').lower() == 'y' or input('Does the search criteria appear in the URL as a parameter?(y/n): ').lower() == 'n' :
print('Framework uses Selenium to scrape project calls')
return True
elif input('Does the website load the entire page at once without delay?(y/n): ').lower() == 'n':
if '<noscript' in response.text:
print('Framework uses Selenium to scrape project calls')
return True
else:
print('Framework uses Scrapy to scrape project calls')
return False
def scrape_data_dynamic(project_links, website_name):
logging.info('Scraping project data...')
body_wait_time = int(input("Enter the amount of time you want to wait for each page to load in seconds: "))
xpath_wait_time = int(input("Enter the amount of time you want to wait for each field to load in seconds: "))
config_xpath = input("Enter the path to your xpath configuration file: ")
ProjectDataSelenium(urls=project_links,
website_name=website_name,
body_wait_time=body_wait_time,
xpath_wait_time=xpath_wait_time,
config_xpath=config_xpath)
def scrape_links_dynamic(start_urls, website_name, config_path):
logging.info('Scraping project links...')
body_wait_time = int(input("Enter the amount of time you want to wait for each page to load in seconds: "))
xpath_wait_time = int(input("Enter the amount of time you want to wait for each field to load in seconds: "))
ProjectLinksSelenium(start_urls=start_urls,
website_name=website_name,
config_path=config_path,
body_wait_time=body_wait_time,
xpath_wait_time=xpath_wait_time)
links = access_stored_links(website_name)
start_urls = [link['project_link'] for link in links]
scrape_data_dynamic(start_urls,website_name)
def scrape_data_static(project_links, website_name, allowed_domains):
config_xpath = input("Enter the path to your xpath configuration file: ")
process = CrawlerProcess()
process.crawl(ProjectDataSpider,
start_urls=project_links,
config_xpath=config_xpath,
website_name=website_name,
allowed_domains=allowed_domains)
process.start()
def scrape_links_static(start_urls,config_path, website_name, allowed_domains):
process = CrawlerProcess()
process.crawl(ProjectLinksSpider,
website_name=website_name,
start_urls=start_urls,
config_path=config_path,
allowed_domains=allowed_domains)
def callback():
links = access_stored_links(website_name)
start_urls = [link['project_link'] for link in links]
scrape_data_static(project_links=start_urls, website_name=website_name, allowed_domains=allowed_domains)
process.crawl(CallbackSpider, callback=callback)
process.start()
links = access_stored_links(website_name)
start_urls = [link['project_link'] for link in links]
scrape_data_static(process=process, project_links=start_urls, website_name=website_name, allowed_domains=allowed_domains)
def access_stored_links(name):
try:
with open(f'./project_links_{name}.json', 'r', encoding='utf-8') as f:
jsonlinks = json.load(f)
return jsonlinks
except FileNotFoundError:
print('File not found')
if is_dynamic():
website_name = input("Enter website name: ")
config_path = input("Enter path to links_config.ini: ")
scrape_links_dynamic(start_urls, website_name, config_path)
else:
website_name = input("Enter website name: ")
config_path = input("Enter the path to links_config.ini: ")
allowed_domains = input("Enter allowed domains: ")
scrape_links_static(start_urls=start_urls, config_path=config_path, website_name=website_name, allowed_domains=allowed_domains)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--start-urls', type=str, help='The start URL of the website to scrape')
args = parser.parse_args()
try:
main(start_urls=args.start_urls)
except (MissingSchema):
logging.error('Please provide the start URL of the website to scrape as string. Example: python main.py --start-urls "https://www.example.com"')
# if input('Do you have to fill out an HTML form to access the project links?(y/n): ').lower() == 'y':
# print('The website is dynamic')
# return True
# # 2
# elif input('Does the search criteria appear in the URL as a parameter?(y/n): ').lower() == 'n':
# print('The website is dynamic')
# return True
# # 3
# elif input('Does the website load the entire page at once without delay?(y/n): ').lower() == 'n':
# print('The website is dynamic')
# return True
# else:
# print('The website is static')
# return False
'''
@@ -1,21 +1,19 @@
[BMBF]
allowed-domain = foerderportal.bund.de
data_set = data_set_BMBF.json
[fields]
Foerderkennzeichen = .//div[@class='detailAnsichtItem']/div[contains(text(),'Förderkennzeichen')]/parent::*/div[2]/text()
Thema = .//div[@class='detailAnsichtItem']/div[contains(text(),'Thema')]/parent::*/div[2]/text()
Verbund = .//div[@class='detailAnsichtItem']/div[contains(text(),'Verbund')]/parent::*/div[2]/form[@id='sucheVerbund']/a/text()
Foerdersumme = .//div[@class='detailAnsichtItem']/div[contains(text(),'Fördersumme')]/parent::*/div[2]/text()
Ressort = .//div[@class='detailAnsichtItem']/div[contains(text(),'Ressort')]/parent::*/div[2]/text()
Projekttraeger = .//div[@class='detailAnsichtItem']/div[contains(text(),'Projektträger')]/parent::*/div[2]/text()
Laufzeit = .//div[@class='detailAnsichtItem']/div[contains(text(),'Laufzeit')]/parent::*/div[2]/text()
Leistungsplansystematik = .//div[@class='detailAnsichtItem']/div[contains(text(),'Leistungsplansystematik')]/parent::*/div[2]/text()
Foerderart = .//div[@class='detailAnsichtItem']/ div[contains(text(),'Förderart')]/parent::*/div[2]/text()
Foerderprofil = .//div[contains(text(),'Förderprofil')]/parent::*/div[2]/text()
Zuwendungsempfaenger = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat des Zuwendungsempfängers']/child::div[2]/text()
Zuwendungsempfaenger_Ort= //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat des Zuwendungsempfängers']/child::div[4]/text()
Zuwendungsempfaenger_Bundesland_stadt = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat des Zuwendungsempfängers']/child::div[6]/text()
Ausfuehrende_Stellen = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat der Ausführenden Stelle']/child::div[2]/text()
Ausfuehrende_Stellen_Ort = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat der Ausführenden Stelle']/child::div[4]/text()
Ausfuehrende_Stellen_Bundesland_Stadt = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat der Ausführenden Stelle']/child::div[6]/text()
Foerderkennzeichen = .//div[@class='detailAnsichtItem']/div[contains(text(),'Förderkennzeichen')]/parent::*/div[2]
Thema = .//div[@class='detailAnsichtItem']/div[contains(text(),'Thema')]/parent::*/div[2]
Verbund = .//div[@class='detailAnsichtItem']/div[contains(text(),'Verbund')]/parent::*/div[2]/form[@id='sucheVerbund']/a
Foerdersumme = .//div[@class='detailAnsichtItem']/div[contains(text(),'Fördersumme')]/parent::*/div[2]
Ressort = .//div[@class='detailAnsichtItem']/div[contains(text(),'Ressort')]/parent::*/div[2]
Projekttraeger = .//div[@class='detailAnsichtItem']/div[contains(text(),'Projektträger')]/parent::*/div[2]
Laufzeit = .//div[@class='detailAnsichtItem']/div[contains(text(),'Laufzeit')]/parent::*/div[2]
Leistungsplansystematik = .//div[@class='detailAnsichtItem']/div[contains(text(),'Leistungsplansystematik')]/parent::*/div[2]
Foerderart = .//div[@class='detailAnsichtItem']/ div[contains(text(),'Förderart')]/parent::*/div[2]
Foerderprofil = .//div[contains(text(),'Förderprofil')]/parent::*/div[2]
Zuwendungsempfaenger = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat des Zuwendungsempfängers']/child::div[2]
Zuwendungsempfaenger_Ort= //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat des Zuwendungsempfängers']/child::div[4]
Zuwendungsempfaenger_Bundesland_stadt = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat des Zuwendungsempfängers']/child::div[6]
Ausfuehrende_Stellen = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat der Ausführenden Stelle']/child::div[2]
Ausfuehrende_Stellen_Ort = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat der Ausführenden Stelle']/child::div[4]
Ausfuehrende_Stellen_Bundesland_Stadt = //div[@class='detailAnsichtItem' and @aria-label='Name, Ort, Bundesland und Staat der Ausführenden Stelle']/child::div[6]
@@ -1,7 +1,3 @@
[DFG]
allowed-domain = gepris.dfg.de
data_set = data_set_DFG.json
[fields]
Title = .//h1[@class='facelift']/text()
Antragsteller = .//div/span[@class='name' and contains(text(), ' Antragsteller')]/parent::*/span[@class='value']/descendant::a/text()
@@ -1,6 +1,3 @@
[EU]
data_set = data_set_EU.json
[fields]
title = //div[contains(@class, 'c-header-project row')]/div[contains(@class, 'c-header-project__title-container')]/h1[contains(@class, 'c-header-project__title')]
objective = //h2[contains(text(), ' Objective ')]/parent::*/p[contains(@class, 'c-article__text')]
+27
View File
@@ -0,0 +1,27 @@
[DFG]
project-list = //div[@class="listbox2"]//div[@id="liste"]/div[@class="eintrag_alternate" or @class=" eintrag"]
project-link = .//div[@class="results"]/h2/a/@href
next-btn = //div[@class="listbox2"]//div[@id="listennavi"]/div[@class="listennaviright"]/a[@class="nextactive"]/@href
[BMBF]
loading-body = //table[@aria-label='Suchergebnis']/tbody/tr
projects-list = //tbody/tr
project-link = .//td/a[@title= 'Detailansicht' and contains(@aria-label, 'Thema')]
next-btn = //form[@id='listnext']/a[@href='#']
search-box = //input[@id='suche_nameZeStSuche']
search-keyword = Universität Duisburg-Essen
search-btn = //input[@id='suche_general_search']
[EU]
loading-body = //section[contains(@class, 'c-search__results')]//app-card-search[@class='ng-star-inserted']
projects-list = //app-card-search[@class='ng-star-inserted']
project-link = .//a[contains(@class, 'c-card-search__title')]
next-btn = //ul[@class='c-pagination__list c-pagination__list--last']/li/a[contains(@class, 'c-pagination__page-link') and contains(@aria-label, 'Goto next page')]
next_disable_condition = c-pagination__page-link--disabled
[test]
loading-body = //body[@class='ux-t-shell-extended']
projects-list = //body[@class='ux-t-shell-extended']//div[contains(@class,'ux-panel-item--no-header')]//div[@class='ux-panel-content']
project-link = .//div[contains(@class, 'topic-title')]/a
next-btn = //p-paginator/div[contains(@class, 'ui-paginator-bottom')]/a[contains(@class, 'ui-paginator-next')]
next_disable_condition = ui-state-disabled
+3
View File
@@ -0,0 +1,3 @@
[fields]
title= //section//h2[contains(@class, 'sedia-title')]
topic-id = //section//h2[contains(@class, 'sedia-title')]/following-sibling::h3/span
+104
View File
@@ -0,0 +1,104 @@
import requests
from scrapy.crawler import CrawlerProcess
from twisted.internet import defer
import argparse
import json
import logging
from requests.exceptions import MissingSchema
from scrapyscript.spiders.project_links import ProjectLinksSpider
from seleniumscript.project_links import ProjectLinksSelenium
from seleniumscript.project_data import ProjectDataSelenium
from scrapyscript.spiders.project_data import ProjectDataSpider
def main(start_urls):
def is_dynamic():
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0'}
response = requests.get(url=start_urls, headers=headers)
if input('Do you have to fill out an HTML form to access the project links?(y/n): ').lower() == 'y' or input('Does the search criteria appear in the URL as a parameter?(y/n): ').lower() == 'n' :
print('Framework uses Selenium to scrape project calls')
return True
elif input('Does the website load the entire page at once without delay?(y/n): ').lower() == 'n':
if '<noscript' in response.text:
print('Framework uses Selenium to scrape project calls')
return True
else:
print('Framework uses Scrapy to scrape project calls')
return False
def scrape_data_dynamic(project_links, website_name):
logging.info('Scraping project data...')
body_wait_time = int(input("Enter the amount of time you want to wait for each page to load in seconds: "))
xpath_wait_time = int(input("Enter the amount of time you want to wait for each field to load in seconds: "))
config_xpath = input("Enter the path to your xpath configuration file: ")
ProjectDataSelenium(urls=project_links,
website_name=website_name,
body_wait_time=body_wait_time,
xpath_wait_time=xpath_wait_time,
config_xpath=config_xpath)
def scrape_links_dynamic(start_urls, website_name):
config_path = input("Enter path to links_config.ini: ")
body_wait_time = int(input("Enter the amount of time you want to wait for each page to load in seconds: "))
xpath_wait_time = int(input("Enter the amount of time you want to wait for each field to load in seconds: "))
logging.info('Scraping project links...')
ProjectLinksSelenium(start_urls=start_urls,
website_name=website_name,
config_path=config_path,
body_wait_time=body_wait_time,
xpath_wait_time=xpath_wait_time)
links = access_stored_links(website_name)
start_urls = [link['project_link'] for link in links]
scrape_data_dynamic(start_urls,website_name)
def crawl_static_website(website_name, start_urls, allowed_domains):
process = CrawlerProcess()
@defer.inlineCallbacks
def scrape_links_static():
config_path = input('Please enter the path to the links configuration file (links_config.ini): ')
yield process.crawl(ProjectLinksSpider, website_name=website_name, start_urls=start_urls, config_path=config_path, allowed_domains=allowed_domains)
yield scrape_data_static()
@defer.inlineCallbacks
def scrape_data_static():
config_xpath = input('Please enter the path to the field configuration file (websitename_config.ini): ')
jsonlinks = access_stored_links(website_name)
links = [link['project_link'] for link in jsonlinks]
yield process.crawl(ProjectDataSpider, website_name=website_name, start_urls=links, config_xpath=config_xpath, allowed_domains=allowed_domains)
scrape_links_static()
process.start()
def access_stored_links(name):
try:
with open(f'./project_links_{name}.json', 'r', encoding='utf-8') as f:
jsonlinks = json.load(f)
return jsonlinks
except FileNotFoundError:
print('File not found')
if is_dynamic():
website_name = input("Enter website name: ")
scrape_links_dynamic(start_urls, website_name)
else:
website_name = input("Enter website name: ")
allowed_domains = input("Enter allowed domains: ")
crawl_static_website(website_name=website_name, start_urls=start_urls, allowed_domains=allowed_domains)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--start-urls', type=str, help='The start URL of the website to scrape')
args = parser.parse_args()
try:
main(start_urls=args.start_urls)
except (MissingSchema):
logging.error('Please provide the start URL of the website to scrape as string. Example: python main.py --start-urls "https://www.example.com"')
@@ -50,6 +50,9 @@
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=01GM2001A"
},
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=01GM2203E"
},
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=01GY1917B"
},
@@ -68,6 +71,9 @@
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=01JA2033A"
},
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=01JA23T01K"
},
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=01JD1800A"
},
@@ -200,6 +206,9 @@
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=03EE5117I"
},
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=03EFVNW324"
},
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=03EI1017A"
},
@@ -374,6 +383,9 @@
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=16SV8663"
},
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=16SV9109"
},
{
"project_link": "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=view&fkz=16TOA014A"
},
@@ -58,8 +58,8 @@
{ "project_link": "https://gepris.dfg.de/gepris/projekt/406521802" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/15478585" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/218135114" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/393022464" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/416858363" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/393022464" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/213739428" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/211126657" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/5322510" },
@@ -86,11 +86,6 @@
{ "project_link": "https://gepris.dfg.de/gepris/projekt/220606072" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/268709653" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/279021035" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/12653476" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/15191758" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/156604961" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/246764666" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/329801962" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/5404910" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/202730120" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/224629024" },
@@ -101,11 +96,16 @@
{ "project_link": "https://gepris.dfg.de/gepris/projekt/318601939" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/320166563" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/406906395" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/12653476" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/15191758" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/156604961" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/246764666" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/329801962" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/28320090" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/147764534" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/206705786" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/27051669" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/241291171" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/27051669" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/173310673" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/258979342" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/52465780" },
@@ -141,6 +141,8 @@
{ "project_link": "https://gepris.dfg.de/gepris/projekt/46834318" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/5467765" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/5406984" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/265592081" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/20292752" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/210421359" }
{ "project_link": "https://gepris.dfg.de/gepris/projekt/210421359" },
{ "project_link": "https://gepris.dfg.de/gepris/projekt/240177810" }
]
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+48534
View File
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -4,8 +4,8 @@
# https://scrapyd.readthedocs.io/en/latest/deploy.html
[settings]
default = Bachelorarbeit.settings
default = scrapyscript.settings
[deploy]
#url = http://localhost:6800/
project = Bachelorarbeit
project = scrapyscript
Binary file not shown.
Binary file not shown.
@@ -6,7 +6,7 @@
import scrapy
class BachelorarbeitItem(scrapy.Item):
class ScrapyscriptItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass
@@ -9,7 +9,7 @@ from scrapy import signals
from itemadapter import is_item, ItemAdapter
class BachelorarbeitSpiderMiddleware:
class ScrapyscriptSpiderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@@ -56,7 +56,7 @@ class BachelorarbeitSpiderMiddleware:
spider.logger.info('Spider opened: %s' % spider.name)
class BachelorarbeitDownloaderMiddleware:
class ScrapyscriptDownloaderMiddleware:
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@@ -8,6 +8,6 @@
from itemadapter import ItemAdapter
class BachelorarbeitPipeline:
class ScrapyscriptPipeline:
def process_item(self, item, spider):
return item
@@ -1,4 +1,4 @@
# Scrapy settings for Bachelorarbeit project
# Scrapy settings for scrapyscript project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
@@ -7,17 +7,17 @@
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'Bachelorarbeit'
BOT_NAME = 'scrapyscript'
SPIDER_MODULES = ['Bachelorarbeit.spiders']
NEWSPIDER_MODULE = 'Bachelorarbeit.spiders'
SPIDER_MODULES = ['scrapyscript.spiders']
NEWSPIDER_MODULE = 'scrapyscript.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'Bachelorarbeit (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
@@ -45,13 +45,13 @@ ROBOTSTXT_OBEY = True
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'Bachelorarbeit.middlewares.BachelorarbeitSpiderMiddleware': 543,
# 'scrapyscript.middlewares.ScrapyscriptSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'Bachelorarbeit.middlewares.BachelorarbeitDownloaderMiddleware': 543,
# 'scrapyscript.middlewares.ScrapyscriptDownloaderMiddleware': 543,
#}
# Enable or disable extensions
@@ -63,7 +63,7 @@ ROBOTSTXT_OBEY = True
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'Bachelorarbeit.pipelines.BachelorarbeitPipeline': 300,
# 'scrapyscript.pipelines.ScrapyscriptPipeline': 300,
#}
# Enable and configure the AutoThrottle extension (disabled by default)
@@ -90,4 +90,3 @@ ROBOTSTXT_OBEY = True
# Set settings whose default value is deprecated to a future-proof value
REQUEST_FINGERPRINTER_IMPLEMENTATION = '2.7'
TWISTED_REACTOR = 'twisted.internet.asyncioreactor.AsyncioSelectorReactor'
FEED_EXPORT_ENCODING = 'utf-8'
@@ -6,21 +6,20 @@ import pandas as pd
import logging
class ProjectDataSpider(scrapy.Spider):
name = 'project-data'
config = ConfigParser()
with codecs.open(os.getcwd() + './Bachelorarbeit/DFG_xpath_config.ini', 'r', encoding='utf-8') as f :
config.read_file(f)
domains = config['DFG']['allowed-domain']
allowed_domains = [domains]
def __init__(self, start_urls=None):
def __init__(self,config_xpath=None, website_name=None, allowed_domains=None, start_urls=None):
super(ProjectDataSpider, self).__init__()
self.start_urls = start_urls.split(',') if start_urls else []
self.allowed_domains = allowed_domains.split(',') if allowed_domains else []
self.start_urls = start_urls
self.website_name = website_name
self.config_xpath = config_xpath
self.config = ConfigParser()
if config_xpath:
with codecs.open(os.getcwd() + config_xpath, 'r', encoding='utf-8') as f :
self.config.read_file(f)
self.items = []
def start_requests(self):
fields = self.config.items('fields')
@@ -30,8 +29,6 @@ class ProjectDataSpider(scrapy.Spider):
def parse(self, response):
fields = response.meta['fields']
item= {}
# item[field_name] = response.xpath("normalize-space(" + xpath + ")").extract() combination of strip() and force_ascii=False
# would produce a clean data set, hence commenting out the normalize-space
for field_name, xpath in fields:
output_list = response.xpath(xpath).extract()
try:
@@ -49,9 +46,7 @@ class ProjectDataSpider(scrapy.Spider):
""" This method is called when the spider is finished scraping.
It takes a reason parameter, which indicates why the spider is closing (e.g. 'finished' or 'shutdown'). """
df = pd.DataFrame(self.items)
df.to_json(self.config['DFG']['data_set'], orient='records', force_ascii=False)
df.to_json(f"scraped_data_{self.website_name}.json", orient='records', force_ascii=False)
+55
View File
@@ -0,0 +1,55 @@
import scrapy
from configparser import ConfigParser
import os
import pandas as pd
import logging
class ProjectLinksSpider(scrapy.Spider):
name = 'links'
def __init__(self, website_name=None, start_urls=None, config_path=None, allowed_domains=None):
super(ProjectLinksSpider, self).__init__()
self.config = ConfigParser()
self.config_path = config_path
self.website_name = website_name
self.allowed_domains = allowed_domains.split(',') if allowed_domains else []
self.start_urls = start_urls.split(',') if start_urls else []
logging.error(self.start_urls)
if config_path:
with open(os.getcwd() + config_path, 'r') as f:
self.config.read_file(f)
self.project_links = []
def start_requests(self):
xpath = dict(self.config.items(self.website_name))
print(xpath)
for url in self.start_urls:
yield scrapy.Request(url=url, callback=self.parse, meta={'xpath':xpath}, dont_filter=True)
def parse(self, response):
xpath = response.meta.get('xpath', {})
# Extract links
for project in response.xpath(xpath['project-list']):
link = response.urljoin(project.xpath(xpath['project-link']).get())
yield{
'link': link
}
self.project_links.append(link)
# Handle pagination
next_page = response.xpath(xpath['next-btn'])
if next_page is not None:
next_url = response.urljoin(next_page.get())
if next_url != response.url:
self.logger.info(f"Following next page: {next_url}")
yield scrapy.Request(url=next_url, callback=self.parse, meta={'xpath':xpath}, dont_filter=True)
else:
self.save_links()
def save_links(self):
df = pd.DataFrame(self.project_links, columns=['project_link'])
df.to_json(f'project_links_{self.website_name}.json', orient='records')
Binary file not shown.
Binary file not shown.
@@ -12,27 +12,29 @@ import os
import pandas as pd
class ScrapeWithSelenium:
def __init__(self, urls):
# self.options = webdriver.ChromeOptions()
# self.options.add_argument('--headless')
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
class ProjectDataSelenium:
def __init__(self, urls, body_wait_time, xpath_wait_time, config_xpath, website_name):
self.options = webdriver.ChromeOptions()
self.options.add_argument('--headless')
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=self.options)
self.config_xpath = config_xpath
self.website_name = website_name
self.driver.maximize_window()
self.body_wait_time=body_wait_time
self.xpath_wait_time=xpath_wait_time
self.urls = urls if urls else []
self.items = []
self.config = ConfigParser()
with codecs.open(os.getcwd() + './Bachelorarbeit/EU_xpath_config.ini', 'r', encoding='utf-8') as f :
with codecs.open(os.getcwd() + config_xpath , 'r', encoding='utf-8') as f :
self.config.read_file(f)
self.run()
def scrape(self, url):
def extract_project_data(self, url):
self.driver.get(url)
item = {}
try:
WebDriverWait(self.driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//body")))
WebDriverWait(self.driver, self.body_wait_time).until(EC.presence_of_all_elements_located((By.XPATH, "//body")))
except TimeoutException as e:
logging.error(f"TimeoutException: {e}. Unable to load the page at URL: {url}")
return None
@@ -42,7 +44,7 @@ class ScrapeWithSelenium:
for field_name, xpath in self.config.items('fields'):
try:
WebDriverWait(self.driver, 1).until(EC.presence_of_element_located((By.XPATH, xpath)))
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.presence_of_element_located((By.XPATH, xpath)))
except NoSuchElementException as e:
logging.error(f"NoSuchElementException: {e}. Unable to find element with xpath {xpath} on page: {url}")
item[field_name] = ""
@@ -58,18 +60,22 @@ class ScrapeWithSelenium:
output_list = self.driver.find_elements(By.XPATH, xpath)
if len(output_list) == 1:
item[field_name] = output_list[0].text
href = output_list[0].get_attribute('href')
item[field_name] = href if href is not None else output_list[0].text
else:
item[field_name] = [output.text for output in output_list]
item[field_name] = [output.get_attribute('href') if output.get_attribute('href') is not None else output.text for output in output_list]
return item
def run(self):
for url in self.urls:
result = self.scrape(url)
result = self.extract_project_data(url)
if result:
self.items.append(result)
self.save_project_data()
def save_project_data(self):
df = pd.DataFrame(self.items)
df.to_json(self.config['EU']['data_set'], orient='records', force_ascii=False)
df.to_json(f"scraped_data_{self.website_name}.json", orient='records', force_ascii=False)
self.driver.quit()
+133
View File
@@ -0,0 +1,133 @@
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import logging
from configparser import ConfigParser
import codecs
import os
import pandas as pd
from selenium.common.exceptions import TimeoutException, NoSuchElementException, StaleElementReferenceException, ElementClickInterceptedException, ElementNotInteractableException
class ProjectLinksSelenium:
def __init__(self, start_urls, website_name, config_path, body_wait_time, xpath_wait_time):
self.start_urls = start_urls
self.website_name = website_name
self.config_path = config_path
self.body_wait_time = body_wait_time
self.xpath_wait_time = xpath_wait_time
self.config = ConfigParser()
with codecs.open(os.getcwd() + config_path, 'r', 'utf-8') as f:
self.config.read_file(f)
self.options = webdriver.ChromeOptions()
#self.options.add_argument('--headless')
self.options.add_argument('--disable-cookies')
self.options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3')
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=self.options)
self.driver.delete_all_cookies()
self.isNextDisabeled = False
self.project_links = []
self.links_config = self.config[self.website_name]
self.driver.get(self.start_urls)
self.driver.maximize_window()
self.fill_out_search_form()
def fill_out_search_form(self):
if 'search-box' in self.links_config and 'search-btn' in self.links_config:
try:
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.presence_of_element_located((By.XPATH, self.links_config['search-box'])))
search_box = self.driver.find_element(By.XPATH, self.links_config['search-box'])
search_keyword = self.links_config['search-keyword']
if search_keyword:
search_box.send_keys(search_keyword)
else:
search_box.send_keys('Universität Duisburg-Essen')
try:
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.presence_of_element_located((By.XPATH, self.links_config['search-btn'])))
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.element_to_be_clickable((By.XPATH, self.links_config['search-btn'])))
search_button = self.driver.find_element(By.XPATH, self.links_config['search-btn'])
search_button.click()
except (TimeoutException, NoSuchElementException, ElementNotInteractableException ) as e:
logging.error(f'Timeout waiting for search button to be clickable: {e}')
try:
WebDriverWait(self.driver, self.body_wait_time).until(EC.presence_of_element_located((By.XPATH, self.links_config['loading-body'])))
except TimeoutException:
logging.error('Timeout waiting for page to load after clicking search button')
return
self.extract_project_links()
except (NoSuchElementException, ElementNotInteractableException) as e:
logging.error(f'Error finding the form elements: {e}')
else:
logging.info('No search form entries found in config file. Extracting project links...')
self.extract_project_links()
def extract_project_links(self):
while not self.isNextDisabeled:
try:
WebDriverWait(self.driver, self.body_wait_time).until(EC.presence_of_element_located((By.XPATH, self.links_config['loading-body'])))
WebDriverWait(self.driver, self.body_wait_time).until(EC.presence_of_all_elements_located((By.XPATH, self.links_config['projects-list'])))
projects = self.driver.find_elements(By.XPATH, self.links_config['projects-list'])
# Extracting project links from a webpage
for project in projects:
try:
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.presence_of_element_located((By.XPATH, self.links_config['project-link'])))
self.project_links.append(project.find_element(By.XPATH, self.links_config['project-link']).get_attribute('href'))
except StaleElementReferenceException as e:
logging.error(f"The reference to the element in the DOM is no longer valid: {e}")
print('error here')
continue
except NoSuchElementException as e:
logging.error(f"NoSuchElementException: {e}")
continue
except TimeoutException as e:
logging.error(f"TimeoutException: {e}")
continue
# Pagination
try:
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.presence_of_element_located((By.XPATH, self.links_config['next-btn'])))
WebDriverWait(self.driver, self.xpath_wait_time).until(EC.element_to_be_clickable((By.XPATH, self.links_config['next-btn'])))
next_btn = self.driver.find_element(By.XPATH, self.links_config['next-btn'])
next_btn_class = next_btn.get_attribute('class')
if 'next_disable_condition' in self.links_config and self.links_config['next_disable_condition'] in next_btn_class:
self.isNextDisabeled = True
else:
self.driver.execute_script("arguments[0].click();", next_btn)
except NoSuchElementException as e:
logging.error(f"NoSuchElementException: {e}")
self.isNextDisabeled = True
except TimeoutException as e:
logging.error(f"TimeoutException: {e}")
self.isNextDisabeled = True
except ElementClickInterceptedException as e:
logging.error(f"Button not clickable: {e}")
self.isNextDisabeled = True
except (TimeoutException, StaleElementReferenceException) as e:
logging.error(f"Failed to load the webpage: {e}")
self.isNextDisabeled = True
self.save_project_links()
def save_project_links(self):
self.driver.quit()
df = pd.DataFrame(self.project_links, columns=['project_link'])
df.to_json(f'project_links_{self.website_name}.json', orient='records')