
########################################################################################################################################

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()